AWRDev.
AWRDev.

Reputation: 45

How to display a certain item from the set C++

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

Answers (3)

Max Langhof
Max Langhof

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

Paul Floyd
Paul Floyd

Reputation: 6906

A description of std::set can be found here. The key points are that

  1. Elements are sorted
  2. Elements are unique
  3. Lookup time is O(lg2(n))
  4. Insertion time is also O(lg2(n))
  5. Element access bidirectional. You can iterate forwards and backward, but you can't select a random element as with 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

  1. Insertion time is O(n)
  2. Element access is random, so you can write tmpSet[8] which whill have O(1) complexity.

Upvotes: 0

con ko
con ko

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

Related Questions