我有一个包含两个成员的结构,一个int和一个字符串。
struct A
{
int a;
string b;
}
vector<A> pl;
pl = getPL(); //getPL returns a vector<A>
for ( auto: pl )
{
vector<A>tr;
tr = getTR() //getTR returns vector<A>
for(auto: tr)
{
//store tr somewhere..
}
}
我想创建一个map<A, vector<A>>
,以便每个pl对象可以容纳一个向量。怎么做?在c ++中是否有任何其他方式或数据结构可以实现我想要做的事情。
谢谢,
答案 0 :(得分:1)
std::map
保持按键排序数据。但要做到这一点,他们需要一些方法来比较两个关键对象,并确定哪一个应该首先出现。默认情况下,此比较是使用<
运算符完成的,但是没有为A
定义该操作,这可能(可能)解释了您(可能)看到的编译错误。
因此;要使用A
作为std::map
中的关键字,您需要为其定义operator <
或为地图提供自定义key_compare
仿函数。下面的代码演示了两种方法:
#include <map>
#include <string>
#include <vector>
struct A
{
int a;
std::string b;
};
bool operator <(const A& l, const A& r)
{
if(l.a != r.a)
return l.a < r.a;
return l.b < r.b;
}
struct B
{
int a;
std::string b;
};
struct CompareBs
{
bool operator()(const B& l, const B& r) const
{
if(l.a != r.a)
return l.a < r.a;
return l.b < r.b;
}
};
int main()
{
std::map<A, std::vector<A>> aMap;
std::map<B, std::vector<B>, CompareBs> bMap;
return 0;
}