search a list?

setting up list
1
2
for(i = 0; i<100; i++)
mylist.pushback(i)


setting my variable
int myvar = mylist.front()

how can i search mylist for myvar without altering anything in mylist? does anyone know the best way to do this?
If that's really just integers you can just iterate over the list and compare each value to the value you're searching for - stuff like binary search would probably end up being slower because you don't have random access with a list.
use std::find(): http://www.cplusplus.com/reference/algorithm/find/

Like so:
1
2
3
4
5
iterator it = std::find(mylist.begin(), mylist.end(), myvar);
if(it != mylist.end())
{
...
}


If you don't want to start from the very beginning:
1
2
3
4
5
6
7
iterator it_begin = mylist.begin();
++it_begin;
iterator it = std::find(it_begin, mylist.end(), myvar);
if(it != mylist.end())
{
...
}
is there any other way than just using find()? since i'm only searching for integers
Iterate over the list and just compare every single item to the search value. That's what std::find does anyways.
Don't avoid the right way just because it is a bit unfamiliar. std::find is the way to go. Yes, you can iterate through the container manually...
1
2
3
4
for( list< int >::const_iterator i = mylist.begin(); i != mylist.end(); ++i ) {
    // print the int
    cout << *i << endl;
}

Note that you will use iterator rather than const_iterator if you need to modify values.
Topic archived. No new replies allowed.