codekiddy
codekiddy

Reputation: 6137

Is an unordered_set modified internally?

I've been reading the cplusplus.com site and trying to make sure that my unordered_set of numbers won't be modified in any way. The site says that the elements of a container are not sorted which is the case with plain set.

The site also says this:

Internally, the elements in the unordered_set are not sorted in any particular order, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their values.

I have no clue what that means really (can you explain btw.?). Consider following example:

typedef const std::unordered_set<short> set_t;
set_t some_set = {1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36};

Can I make sure that the above set "some_set" will never be changed and that the numbers will always stay in the same order (because this is the goal here)? I'm also not planning to insert or remove numbers from the set.

Upvotes: 1

Views: 85

Answers (1)

Travis Gockel
Travis Gockel

Reputation: 27633

typedef const std::unordered_set<short> set_t;
set_t some_set = {1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36};

The changing order of the numbers in some_set depends on the operations that you do to some_set. The contents of some_set immediately after creation is not defined, but it probably won't be {1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36}. You can see this with a simple demo:

#include <iostream>
#include <unordered_set>

int main() {
    typedef const std::unordered_set<short> set_t;
    set_t some_set = {1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36};

    for (short s : some_set)
        std::cout << s << std::endl;

    // The order won't change if we don't modify the contents
    std::cout << "AGAIN!" << std::endl;
    for (short s : some_set)
        std::cout << s << std::endl;

    // If we put a bunch of stuff in
    for (short s = 31; s < 100; s += 4)
        some_set.insert(s);

    // The elements from *before* the modification are not necessarily in the
    // same order as before.
    std::cout << "MODIFIED" << std::endl;
    for (short s : some_set)
        std::cout << s << std::endl;
}

Upvotes: 1

Related Questions