Is it impossible to use an STL map together with a struct as key?

前端 未结 6 2191
离开以前
离开以前 2020-12-14 03:46

I have the following code:

struct Node
{
  int a;
  int b;
};

Node node;
node.a = 2;
node.b = 3;

map aa;
aa[1]=1; // OK.

map

        
6条回答
  •  独厮守ぢ
    2020-12-14 04:13

    As a std::map is sorted by its keys, you have to define how to compare two Node objects. Since C++11 you can also use a lambda expression instead of defining a comparison operator. As a result, you can keep your code as short as follows:

    int main() {
        Node node{ 2, 3 };
    
        auto comp = [](const Node& n1, const Node& n2) {
            return n1.a < n2.a || (n1.a == n2.a && n1.b < n2.b);
        };
        std::map bb(comp);
        bb[node] = 1;
    
        for (auto const &kv : bb)
            std::cout << kv.first.a << ", " << kv.first.b << ": " << kv.second << std::endl;
    
        return 0;
    }
    

    Output:

    2, 3: 1

    Please replace the body of the lambda expression according to your needs.

    Code on Ideone

提交回复
热议问题