是不是可以在结构中使用stl map?

Cod*_*Lab 14 c++ containers dictionary stl stdmap

struct Node
{
  int a;
  int b;
};

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

map<int, int> aa;
aa[1]=1; // OK.

map<Node, int> bb;
bb[node]=1; // Compile error.
Run Code Online (Sandbox Code Playgroud)

当我尝试将结构映射到int时,它给了我一个编译错误.为什么?谢谢!

小智 23

对于可用作地图中的键的东西,您必须能够使用它进行比较operator<().您需要将这样的运算符添加到节点类:

struct Node
{
 int a;
 int b;

 bool operator<( const Node & n ) const {
   return this->a < n.a;   // for example
 }
};
Run Code Online (Sandbox Code Playgroud)

当然,真正的运算符所做的取决于比较对于你的结构实际意味着什么.


sel*_*tze 10

你必须告诉std :: map如何比较Node对象.默认情况下,它尝试使用小于运算符.但是你没有为Node提供任何运算符.最简单的解决方案是提供一个.

自由功能示例:

bool operator<(Node const& n1, Node const& n2)
{
    return n1.a<n2.a || (n1.a==n2.a && n1.b<n2.b);
}
Run Code Online (Sandbox Code Playgroud)

注意,对于任何一对节点对象x,y with !(x<y)!(y<x)map将把x和y视为相等(相同的键).


mlo*_*kot 7

您需要定义less-than运算符以启用Node类型的比较:

struct Node
{
 int a;
 int b;
};

bool operator<(Node const& n1, Node const& n2)
{  
   // TODO: Specify condition as you need
   return ... ;
}
Run Code Online (Sandbox Code Playgroud)

在这里,您可以检查LessThan Comparable对于用户定义类型的含义.

替代解决方案是基于std :: binary_function定义仿函数.从设计的角度来看,这个选项具有优势,因为比较与Node类有效地分离.这使得可以定义专门用不同比较条件(仿函数)的地图.

#include <map>

struct Node
{
 int a;
 int b;
};

struct NodeLessThan
    : public std::binary_function<Node, Node, bool>
{
    bool operator() (Node const& n1, Node const& n2) const
    {
        // TODO: your condition
        return n1.a < n2.a;
    }
};

int main()
{
    Node node;
    node.a = 2;
    node.b = 3;

    typedef std::map<Node, int, NodeLessThan> node_map_t;
    node_map_t bb;
    bb[node] = 1;
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以定义更多的比较,而不仅仅是NodeLessThan,例如使用不同的条件或仅Node::a比较另一个比较两个组件,Node::aNode::b.然后,定义不同类型的地图:

typedef std::map<Node, int, NodeLessThan>    node_map_t;
typedef std::map<Node, int, NodeLessThanByA> node_map_a_t;
Run Code Online (Sandbox Code Playgroud)

这种解耦不那么具有侵入性(根本不接触Node类),并且有利于实现更具可扩展性的解决方案.