Hi, I'm a total newb at c++, and I was wondering if I could get any advice on how to find the largest element of a vector argument. I kept reading through the forums and they all use max_element but I don't know anything about pointers, and I'd like to keep it to what I know as of right now (Ch. 11 of stroustrup).
#include <algorithm>
#include <vector>
/*...*/
std::vector<int> data;
//initialize vector
int max = *max_element(data.begin(), data.end()); //Look ma, no pointers
2nd version:
1 2 3 4 5 6 7 8 9 10
#include <vector>
/*...*/
std::vector<int> data;
//initialize vector
int max = data[0];
for(int i = 0; i < data.size(); ++i)
if (max < data[i])
max = data[i];
That is the dereference operator used for dereferencing a pointer.
Also depending on how you fill your vector you could simply have a variable to keep track of the max value before adding them to the vector.
1 2 3 4 5 6 7 8 9 10 11 12 13
std::vector<int> data;
int max =0;
int input;
for( int i = 0; i < 20; ++i )
{
std::cout << "Please enter an integer: ";
std::cin >> input;
if( input > max )
{
max = input;
}
data.push_back(input);
}
First and second version of code do the same thing. First one just uses already written algorithm from standard library. giblit's code avoid second vector pass as it finds maximum during input. When speed is critical it is often important. And it is always nice to know that there is other ways to do something.
Another thing to mention is if you have a lot of data you may want to reserve some memory before adding new elements or you may allocate extra times than needed.