Reputation: 45
I have a set, let's say set<string>tmpSet
. I have some elements in it,for example 10
, but I don't know what they are, because I've got this set by set_intersection
of two another sets. Can I display for example just first, third and eighth
element from the set?
Upvotes: 1
Views: 897
Reputation: 23681
Yes.
std::set<std::string> tmpSet = ...; // Create your set somehow.
// Get an iterator to the first (smallest) item in the set.
std::set<std::string>::iterator setStartIt = tmpSet.begin();
// Dereference the iterator to obtain a reference to the first element.
std::string& firstItem = *setStart;
// Get an iterator for the third element (this is two after the first!).
auto thirdItemIt = std::next(setStartIt, 2);
std::string& thirdItem = *thirdItemIt;
// Get the tenth item.
std::string& tenthItem = *std::next(setStartIt, 9);
Note that you can also use std::advance()
(which modifies the iterator you pass instead of returning a new one.
Also keep in mind that this is not efficient: Since the std::set
iterator is not a RandomAccessIterator
, the complexity of std::next
and std::advance
are linear (so it will take 10 operations to get the 10th item).
If you want to look at all elements, looping over them would of course be the proper way:
for (auto it = tmpSet.begin(); it != tempSet.end(); ++it) {
std::string currentElement = *it;
...
}
Or, using a range-based for loop:
for (auto& currentElement : tmpSet)
...
Upvotes: 1
Reputation: 6906
A description of std::set can be found here. The key points are that
tmpSet[8]
. This means O(n) access time for random elements.If you do want to have random access, you could use a boost::flat_set. This has the same properties as above except
tmpSet[8]
which whill have O(1) complexity.Upvotes: 0
Reputation: 1388
The elements in a std::set
are always in order (sets are typically implemented as red-black tree
).That interesting property, of course, can be used.
By using range-based for
(since Cpp11) or search the section between set::begin()
and set::end()
, you can insure the elements inside.
Here is the reference http://en.cppreference.com/w/cpp/container/set
Upvotes: 0