kvway
kvway

Reputation: 494

Accessing structure elements using iterator

I have defined this structure and vector:

struct All
{
    string name;
    int id;
};
vector<All*> all;

I'm inserting created structure with data to the vector using lower_bound function to keep it sorted.

All * tmp = new All(name, id);
auto it = lower_bound(all.begin(), all.end(), name, compare2());
all.insert(it, tmp);

When I want to find the structure with name = test I do this :

auto it1 = lower_bound(all.begin(), all.end(), name, compare2());

It gives me iterator it to that structure with name containing test in it but why can't I access the elements of the structure like this cout << it1 -> id;? How can I access elements of that structure?

Upvotes: 1

Views: 546

Answers (2)

MikeMB
MikeMB

Reputation: 21166

You have to dereference your iterator a second time, in order to access the fields of the datastructure:

(*it1)->id;

Explanation:

Conceptually, iterators are little more than pointers to an element in the container (in fact, most implementations of std::vector<T>::iterator are pointers to T). In your case, the container element is a pointer itself, so you have to dereference the iterator two times: The first (*it) gives you a reference to the pointer stored in the container which is then dereferenced by the -> operator to give access to the actual object field.

The way you wrote it you where trying to access a member of the iterator (which doesn't have any if it is implemented as a raw pointer)

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

You can do it the following way

cout << ( *it ) -> id;

Expression *it gives the element in the vector that is a pointer.

Upvotes: 2

Related Questions