Pointers and std::list

Started by
6 comments, last by Hedos 19 years, 11 months ago
Hey, I recently tried to do something with std::list but I got a problem.. I'm trying to do this: --edit-- see my second post for the correct exemple The "iter==ptr" gives me this error: "error C2679: binary '==' : no operator defined which takes a right-hand operand of type 'class std::list >::iterator' (or the re is no acceptable conversion)" What is wrong? When I'm doing the exact same thing with a vector, it works fine.. :/ How could I make this work? Thanks [edited by - Hedos on May 8, 2004 12:52:06 AM] [edited by - Hedos on May 9, 2004 8:25:39 PM]
Advertisement
What is wrong?
A list iterator is not a pointer.

When I''m doing the exact same thing with a vector, it works fine.. :/
Pure accident. Implementation-specific. Don''t rely on it.

How could I make this work?
As it is currently, it cannot work. The object placed in the list is a copy of MyObj, not MyObj itself (I assume that''s what you meant). It is therefore located at a different address.

If MyClass supports it (or if you use a type for which that operation is legal) you can, however, test for object equality.

if (*iter==MyObj)

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” — Brian W. Kernighan
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
oh, damn, my exemple was wrong, sorry...

This is the correct exemple I should have given:
MyClass MyObj;MyClass *ptr;std::list<MyClass> MyList;MyList.push_back(MyObj);std::list<MyClass>::iterator iter;iter=MyList.begin();ptr = iter;if(iter==ptr){  //Do something}


Well, this would work fine with vectors and as I far as I know, iterators are kinda like pointers.. so there must be a wait to do it with list iterators too?
How about ptr = &*iter.
---Mikael Lax
You''ve made a /copy/ of MyClass''s in the list, so you cannot test for equality by using the identity (address of/pointer to).
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Hum.. there must be a way to have the address of the element in the list that my iterator is referencing to?
That's the only thing I need to do

quote:Original post by TheSalmon
How about ptr = &*iter.


Gives me an "Access Violation." :/

[edited by - Hedos on May 9, 2004 2:08:37 PM]
Up..

No one know if it''s possible to get the address of an element "referenced" in a std::list iterator?
i have always done it in the way described above as well and never had a problem. eg.

std::list::iterator it = aList.begin();

MyClass* myclass = &(*it);

This topic is closed to new replies.

Advertisement