Question:
Can't get this C++ program to compile? Need help with iterators?
anonymous
2008-07-30 11:52:38 UTC
I need a little help iterating through an inventory vector. I was playing around last night with making a text-based game called World of Textcraft, and I'm trying to use an iterator to search through a vector to find a required item. One thing before I continue: I made this program very quickly and as a sort of joke. I know I didn't code it with the best style, I know all of these nested case statements are probably not the best way to make all of those decisions. However, I just want to understand this whole "iterator" thing, which means understanding why I can't search through my inventory vector. The code is included in the "extra details" section.

Thanks.
Three answers:
VarmintHunter07
2008-07-30 13:37:41 UTC
An iterator is really just a pointer. The vector::begin() method returns a pointer to the first element in the vector. This pointer can then be dereferenced to access the pointed to element or incremented to iterate to the next element in the collection. You'd stop incrementing once your iterator got to vector::end() which points to the position after the last element in the collection.



To find an item in a vector:



std::vector itemVector;

for ( std::vector::iterator iter = itemVector.begin();

iter != itemVector.end(); ++iter )

{

item = *iter;

if ( item == matchingItem )

{

break;

}

}



Note however, that elements in a vector don't need to be unique. You may have multiple identical elements. If you need uniqueness, you should use a std::set which can be iterated in the same fashion.



Look at the std::find() method declared in which may simplify your search.
gabriela
2016-05-23 08:39:05 UTC
There is a problem with your compiler.Copy the path to your header files from the address bar and paste it in the path for your compiler in Set Directories. If this doesn't help,try reinstalling the program,but use a different setup for that.
Neebler
2008-07-30 13:14:41 UTC
To use a vector like you are, its easier to treat it as an array and use an int index:



for (int a=0; a < (int)vec.size(); ++a) {

vec[a].dosomething();

}



To do this same loop with an iterator:



for (vector::iterator it = vec.begin(); it != vec.end(); ++it) {

(*it).dosomething();

}



When you use more complex containers like deques and lists, then iterators really become necessary.



You should also look at the algorithm header. There's lots of iterator goodness to chew on there.



BTW a good code pasting site:



http://pastebin.com/


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...