C++ 创建C++;从复合键映射
我想创建一个包含复合键的映射。例如,我有学生卷号和他/她正在学习的学期。现在我想创建一个映射,使roll no和Serm一起作为映射的键。编辑:片刻的怀疑使我怀疑C++ 创建C++;从复合键映射,c++,map,C++,Map,我想创建一个包含复合键的映射。例如,我有学生卷号和他/她正在学习的学期。现在我想创建一个映射,使roll no和Serm一起作为映射的键。编辑:片刻的怀疑使我怀疑操作符==()是否也必须由键类型提供,因为显然在映射中查找值时,必须在引擎盖下使用相等性测试。但2003 C++标准中的23.1.2/3称这是不必要的:需要检查两个关键对象的相等性:代码> A和代码> B/COD>。p> #包括 结构键{ int-rollNo; 学期内; 不管是什么,都要串起来; //为键搜索和插入提供“std::ma
操作符==()
是否也必须由键类型提供,因为显然在映射中查找值时,必须在引擎盖下使用相等性测试。但2003 C++标准中的23.1.2/3称这是不必要的:需要检查两个关键对象的相等性:代码> A<代码>和代码> B/COD>。p>
#包括
结构键{
int-rollNo;
学期内;
不管是什么,都要串起来;
//为键搜索和插入提供“std::map键需要实现运算符<”。
例如:
#include <map>
struct Student
{
Student(int roll_no, int semestre)
: roll_no(roll_no), semestre(semestre)
{}
int roll_no;
int semestre;
bool operator< (Student const &s) const
{
return semestre* 100000+ roll_no< s.semestre* 100000+ s.roll_no;
}
};
#include <iostream>
#include <ostream>
int main()
{
std::map<Student, int> m;
m[Student(1, 1)]= 42;
m[Student(1, 2)]= 43;
std::cout<< m[Student(1, 1)];
}
#包括
体类型
{
学生(国际卷号,国际学期)
:卷号(卷号),半卷(半卷)
{}
国际卷号;
国际货币基金组织;
布尔运算符<(学生常量和s)常量
{
返回semestre*100000+卷号 std::cout您可以定义包含卷号和学期成员的结构类型
struct stu_key
{
int roll_no;
int semester;
bool operator <(const stu_key &sk) const
{
//compare roll_no and semester
}
};
std::map<stu_key , value_type> stu_map;
struct stu\u key
{
国际卷号;
学期内;
bool操作符由于您只关心卷号和学期,因此我将使用std::pair,而不是为键定义您自己的类和必须定义您自己的比较操作符
#include <utility>
#include <map>
// This maps an std::pair of (roll number, semester) to a StudentRecord.
std::map<std::pair<int, int>, StudentRecord> studentMap;
studentMap.insert(std::pair<std::pair<int, int>, StudentRecord>(std::make_pair(100, 100), StudentRecord());
#包括
#包括
//这将std::一对(卷号,学期)映射到StudentRecord。
std::map studentMap;
insert(std::pair(std::make_pair(100100),StudentRecord());
如果你对卷号和学期使用的不是int,那么你也可以很容易地在对中使用它们。请记住,如果你对这些对象使用自定义结构,它们将需要实现相等和比较运算符,在这种情况下,你将失去使用对而不是使用其他结构的好处直接正确。我认为OP希望学生
是映射类型,并使用学生
数据使用一个单独的键。OP:semestre
乘以100000的效果是允许使用单个整数比较来完成比较。如果你确信roll\u no
永远不会发生,这是一种方便的技术xceed 99999。@j_random_hacker这正是我想演示的。我有老板在身,所以我必须很快完成:这是一个更好、更通用的答案,因为std::pair已经有了必要的比较器来充实@pwned的备注:类型std::pair
将通过@pwned自动进行比较如果比较需要更多的字段,d会很快变得难看。幸运的是C+11有std::tuple
如果你确实需要更多的字段进行比较,那么定制结构无疑是一种方法。然而,鉴于OP说卷号和学期为学生定义了一个唯一的自然键,似乎不太可能有更多的f如果(ab)返回false;
,那么你就不需要嵌套ifs了。@ybungalobill:好主意,不过我建议如果(b@j_random_hacker:或者更简单的=>boost::tie(这个->罗尔诺,这个->学期,这个->其他)
,元组默认按字典顺序排列;)Theoperator@j_random_hacker是的,我已经更改了。+1,但是最好去掉typedef
并将参数调用到操作符
#include <utility>
#include <map>
// This maps an std::pair of (roll number, semester) to a StudentRecord.
std::map<std::pair<int, int>, StudentRecord> studentMap;
studentMap.insert(std::pair<std::pair<int, int>, StudentRecord>(std::make_pair(100, 100), StudentRecord());