tags:

views:

138

answers:

3

What exactly must I replace ??? with to get the iterator (it) to some element (for example Base(2)) ?

I tried a few shots but nothing, compiler just says that it is wrong.

Here is code

#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;

class Base
{
    public:
    Base(int a) {ina = a;}
    ~Base()  {}
    int Display() {return ina;} 

    int ina;
};

int main(int argc, char *argv[]) 
{
    vector<Base> myvector;

    for(int i=0 ; i<10 ; i++)
    {
     myvector.push_back(Base(i));
    }

    vector<Base>::iterator it;

    it = find(myvector.begin(), myvector.end(), ??? );

    system("PAUSE");
    return EXIT_SUCCESS;
}

Thanks in advance !

+2  A: 

You can just do myvector.begin() + n to get an iterator to the nth element of myvector.

Jacob B
With "nth element" meaning "the element at index n" (just to clarify).
sth
A: 

http://www.cplusplus.com/reference/algorithm/find/

The third argument is basically the value you're "comparing" for.

Suvesh Pratapa
+6  A: 

The third parameter is just the value you look for.

it = find(myvector.begin(), myvector.end(), Base(2));

The problem is now that the compiler needs to know whether two elements are equal. So you'll have to implement an operator for equality-checking (write this code between main and your class definition):

// a equals b if a.ina equals b.ina
bool operator == (const Base& a, const Base& b) {
    return a.ina == b.ina;
}

If you just want to get the nth element of myvector, you can also just write myvector.begin() + n.

Dario
Thanks !!! that is what I looking for
I was trying with Base(2) but without implementation of bool operator.That's was the catch.Thank's again.