1

This has been asked for vectors. But is this possible for sets & Co too?

Community
  • 1
  • 1
ManuelSchneid3r
  • 15,850
  • 12
  • 65
  • 103

3 Answers3

1

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);
thinkerou
  • 1,781
  • 5
  • 17
  • 28
0
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).

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
0

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.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455