crazy_balance
crazy_balance

Reputation: 139

C++ - What is the fastest way to search for all the keys with same value in a map?

Let's say we have an initialized map:

const std::map<int, std::string> map = {
    { 0, "A" },
    { 1, "B" },
    { 2, "A" },
    { 3, "A" },
    { 4, "C" },
    { 5, "A" },
    // ...
};

What is the fastest method to retrieve all the keys associated with the value "A" in a scenario where there would be between 1 and 1000 values?

Upvotes: 0

Views: 600

Answers (2)

YSC
YSC

Reputation: 40070

With an std::map which contains no index on its values, you can only do:

#include <iostream>
#include <map>
#include <string>

int main()
{
    const std::map<int, std::string> map = {
        { 0, "A" },
        { 1, "B" },
        { 2, "A" },
        { 3, "A" },
        { 4, "C" },
        { 5, "A" },
    };

    for (const auto& pair : map) {
        if (pair.second == "A") {
            std::cout << '{' << pair.first << ", " << pair.second << "}\n";
        }
    }
}

Upvotes: 1

James Dong
James Dong

Reputation: 404

You can use Boost.Bimap. Boost.Bimap is a bidirectional maps library for C++. With Boost.Bimap you can create associative containers in which both types can be used as key.

Upvotes: 3

Related Questions