This has been asked for vectors. But is this possible for sets & Co too?
-
No, at least not for arbitrary containers. Lookup for iterator traits and concepts. – πάντα ῥεῖ Apr 01 '15 at 11:14
-
What's & co cover? basically no – EdChum Apr 01 '15 at 11:14
-
Set, multiset, map, multimap. [Check this](http://www.cplusplus.com/reference/stl/) – ManuelSchneid3r Apr 01 '15 at 11:16
-
@ManuelSchneid3r http://en.cppreference.com/w/cpp/iterator/iterator_tags – πάντα ῥεῖ Apr 01 '15 at 11:17
-
It might be easier to understand this question if you make it clear exactly what you have. E.g. `std::set
` and `"banana"`. – MSalters Apr 01 '15 at 13:57
3 Answers
set have find function that it returns iterator
const_iterator find (const value_type& val) const;
iterator find (const value_type& val);
eg:
std::set<int> s;
std::set<int>::iterator it;
it = s.find(v);

- 1,781
- 5
- 17
- 28
c.equal_range(elem);
for set-like, or
c.equal_range(elem.first);
for map-type containers will return a pair of iterators that are equivalent (under the container's rules) to the element. This takes between O(k) and O(lg n) time, where n is the number of elements in the container, and k is the number of elements pseudo-equivalent to elem
/elem.first
(pseudo, as hash collisions modulo bucket count also count). Average is constant (for unordered)/lg n (for ordered).

- 262,606
- 27
- 330
- 524
Associative containers are pretty much designed to find iterators to a given element. So just use the container's find
function. Note that it's not constant time, it will have time complexity of the container's lookup (logarithmic for ordered containers, average constant for unordered containers):
auto iteratorToElement = container.find(element);
If you need to be able to do this in constant time, you might want to use Boost.MultiIndex instead, which has this functionality.

- 167,307
- 17
- 350
- 455