Trouble with vectors

Feb 26, 2014 at 6:56pm
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).
Feb 26, 2014 at 7:30pm
1st version:
1
2
3
4
5
6
7
8
#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];
Feb 26, 2014 at 7:50pm
Thanks but what does the *do before max_element?
Feb 26, 2014 at 7:54pm
It dereferences iterator returned by max_element. Basically it extracts value from pointer.
Feb 26, 2014 at 7:56pm
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);
}
Feb 26, 2014 at 8:02pm
If you're just comparing an endless amount of values would you just basically do what the second version of the code did?
Feb 26, 2014 at 8:06pm
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.
Last edited on Feb 26, 2014 at 8:06pm
Feb 26, 2014 at 8:08pm
Thanks you guys! Really appreciate it!
Feb 26, 2014 at 8:11pm
endless amount

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.
Topic archived. No new replies allowed.