Masoud
Masoud

Reputation: 1405

isn't iterator an object?

this is my code:

for (list<moveStringTree>::iterator tempIterator=moveList.begin();tempIterator!=moveList.end(); ++tempIterator)
{
    moveStringTree *move = tempIterator;
}

but it gives me an error. if there is a castingway, I don't like it. it is too time consuming. anyway I want to go throw a list and do something with each object in it. what can I do? foreach won't help. because only it will give a copy.

Upvotes: 0

Views: 175

Answers (4)

Matteo Italia
Matteo Italia

Reputation: 126777

Try:

moveStringTree *move = & (*tempIterator) ;

(the parentheses aren't strictly necessary)

The iterator itself is not a pointer to the object, but overloads * to return a reference to the object it refers to; from it you can get a pointer using the normal &.

Notice that normally you don't need to do this, since the iterator overloads also the -> operator, so you can access the object's members using the usual -> syntax.

Upvotes: 2

Konrad Rudolph
Konrad Rudolph

Reputation: 545518

isn't iterator an object?

It is. An object in C++ is equivalent to a memory location holding a value – no more, no less. However, I don’t see how this relates to the rest of the question.

but it gives me an error. if there is a castingway, I don't like it. it is too time consuming.

I have no idea what this means. But just in case you meant copy: no, it’s probably not too time-consuming. But if it is – don’t worry; use a reference.

moveStringTree& move = *tempIterator;

foreach won't help. because only it will give a copy.

Nonsense. foreach does the same as manually iterating. So you can also use it with a copy:

for (auto& o : moveList) {
    // Do something.
}

Upvotes: 3

Puppy
Puppy

Reputation: 146910

In fact, you can gain a reference from std::for_each. moveStringTree* move = &*tempIterator; would be correct. However, more directly, you can simply use tempIterator as if it was already a pointer to the object in question.

for(auto it=moveList.begin();it!=moveList.end(); ++it) {
    it->f(); // well formed if moveStringTree::f()
}

Upvotes: 1

John Calsbeek
John Calsbeek

Reputation: 36497

You can use an iterator as if it was a pointer, but it isn't actually one. There is a dance that you can do to grab a pointer out of it, though:

moveStringTree *move = &*tempIterator;

The * resolves to a reference to the element that the iterator refers to, and the & returns the address of that element. The end result is a pointer.

Of course, you probably shouldn't do that. This:

tempIterator->doSomething();

works just fine.

Upvotes: 2

Related Questions