【发布时间】:2023-03-12 04:50:01
【问题描述】:
这是带有字符串键和结构值的映射
1.首先,我正在创建一个整数映射和一个结构作为值
std::map<int,struct value>; 然后我将所有这些地图对象添加到一个集合中
std::set<std::map<int,struct value>> 我想了解如何循环遍历这个集合
我无法访问该集合中的地图,请建议
struct values
{
std::string a;
std::string b;
values():a("milepost"),b("dummyval"){};
values( std::string ab, std::string bc)
{
a=ab;
b=bc;
};
bool operator<(const values& other) const {
return (a< other.a && b < other.b) ;
}
friend std::ostream& operator<<(std::ostream& os, const values& val);
};
std::ostream& operator<< (std::ostream& os , const values& val)
{
os << val.a <<"\t"<< val.b;
return os;
}
typedef std::map<std::string,values> myWsData;
main()
{
values a;
myWsData et_Data1,pt_Data2;
et_Data2.insert(std::make_pair("780256", a));
pt_Data2.insert(std::make_pair("780256", a));
std::set<myWsData> myet_pt_data;
myet_pt_data.insert(et_Data1);
myet_pt_data.insert(pt_Data2);
for (auto &i:myet_pt_data)
{
std::cout<<i<<"\n";
}
}
【问题讨论】:
-
Iam not able to access the maps that are the part of this set,请详细说明....您的问题是什么:编译?运行?你有什么经历让你觉得它不起作用? -
你会遇到两个地图的小于比较的问题,不是吗?你真正想解决什么问题?
-
@RichardHodges 我认为(因为他还是个学习者)我们应该补充一点,小于比较是必要的,因为
std:set被实现为 sorted 设置。因此,我们需要定义此代码缺少的元素的顺序。 -
@Christoph :这是否意味着 std::set 中的模板值需要有一个比较运算符,除非它是一个 pod
-
@LearningCpp
std::set的完整模板是template< class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key> > class set;。因此,std::less<Key>对您的类型有效(例如,默认情况下或因为您已定义它),或者您必须使用定义元素顺序的比较器覆盖Compare。