Using efficient containers

suggest change

Optimizing by using the right data structures at the right time can change the time-complexity of the code.

// This variant of stableUnique has complexity N log(N)
// N = number of elements in v
// log(N) = insert complexity of std::set
std::vector<std::string> stableUnique(const std::vector<std::string> &v) {
    std::vector<std::string> result;
    std::set<std::string> checkUnique;
    for (const auto &s : v) {
        // See Optimizing by executing less code
        if (checkUnique.insert(s).second)
            result.push_back(s);
    }
    return result;
}

By using a container which uses a different implementation for storing its elements (hash container instead of tree), we can transform our implementation to expected complexity N. As a side effect, std::string is tested with operator== rather than an ordering comparison, and only for keys that land in the same bucket. Worst-case unordered_set insertion is still linear.

// This variant of stableUnique has average complexity N
// N = number of elements in v
// 1 = average insert complexity of std::unordered_set
std::vector<std::string> stableUnique(const std::vector<std::string> &v) {
    std::vector<std::string> result;
    std::unordered_set<std::string> checkUnique;
    for (const auto &s : v) {
        // See Optimizing by executing less code
        if (checkUnique.insert(s).second)
            result.push_back(s);
    }
    return result;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents