C++: getting index of an item in a container

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
std::find() will return an iterator to it, but I can't seem to find anything that returns the offset of an item in a container. I made this (index_of() specifically) for the time being, but this seems like such a common thing that it would be in the STL, is it somewhere and I'm missing it?
 

ElDonAntonio

Senior member
Aug 4, 2001
967
0
0
Say you have a vector:

std::vector<item> MyVector;

std::vector<item>::iterator it = find(...);
int index = it-MyVector.begin();

or even simpler:

int index = find(...) - MyVector.begin();

voila!
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Doh.. doesn't seem to work (with a list<> anyways)

bool WindowPool::screenNumberOfRoot(Window root, int * screennum_return) {
list<Window>::iterator found = find(roots.begin(), roots.end(), root);

if(found == roots.end())
return false;

*screennum_return = found - roots.begin();
return true;
}

I get this nasty complaint:

WindowPool.cc:97: error: no match for 'operator-' in 'found - std::list<_Tp, _Alloc>::begin() [with _Tp = Window, _Alloc = std::allocator<Window>]()'
/usr/include/c++/3.3/bits/stl_bvector.h:147: error: candidates are: ptrdiff_t std::eek:perator-(const std::_Bit_iterator_base&, const std::_Bit_iterator_base&)

Hmmm.. it seems that iterator subtraction only needs to be supported by random access iterators, which I assume a list<>::iterator is not. Bah.. maybe I'll just use a vector instead.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Cool. I've been sifting through SGI's STL docs trying to absorb all of the useful looking stuff but I never saw distance(). It sounds like it would be less efficient, I would need to iterate through twice (once in find() and once in distance()) to get the offset. But actually a vector is fine for this, it'll only be holding a handful of items at the very most.
 

glugglug

Diamond Member
Jun 9, 2002
5,340
1
81
If you aren't frequently inserting/removing stuff from the middle of the list, a vector is more efficient anyways.
 

glugglug

Diamond Member
Jun 9, 2002
5,340
1
81
Random access and searching both, although searching is to a much lesser extent.
 

glugglug

Diamond Member
Jun 9, 2002
5,340
1
81
vectors are bad at random insertions & deletions. (Insertion/deletion only works well at the end of the vector). Random access as in reading or changing the value at a given position they are great at.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Originally posted by: glugglug
vectors are bad at random insertions & deletions. (Insertion/deletion only works well at the end of the vector). Random access as in reading or changing the value at a given position they are great at.

Ahh that makes more sense.