0 c++ struct iterator insert map
当我使用operator []在c ++映射中插入元素时会发生错误.
我有这个地图<Pair,int>变量.当我向其中插入一个新元素,然后使用迭代器打印其键时,地图的某些元素会随机消失,并且值不会按递增顺序打印.但是,当我使用funtion insert()插入元素时,一切正常.我对operator []做错了什么?两种情况下结果不一样吗?
备注:每个密钥对是一个存储一对整数的结构.
这是一个例子:我插入以下六个键(5,9),(5,11),(5,12),(4,14),(1,10),(3,10).然后,我迭代地图,键(3,10)消失.此外,元素不按顺序打印.要查看应该打印的正确方法,请按照下面代码注释中的说明进行操作.
这是我的代码:
#include <iostream>
#include <map>
using namespace std;
struct Pair {
int a;
int b;
Pair(const int& a,const int& b) { //assures the first int is the smaller one
if (a < b) {
this->a = a;
this->b = b;
} else {
this->b = a;
this->a = b;
}
}
bool operator<(const Pair& otherPair) const {
return this->a < otherPair.a || this->b < otherPair.b;
}
};
int main() {
Pair elements []{ Pair (5,9), Pair (5,11), Pair (5,12), Pair (4,14), Pair (1,10), Pair (3,10) }; // keys to insert into the map
map<Pair,int> mapPairInt; // map to store the elements
for(int i = 0; i <6;i++){
mapPairInt[elements[i]] = 0; //insert elements using operator[]
//mapPairInt.insert ( std::pair<Pair,int>(elements[i],0) ); // insert elements using insert() -- uncomment this line and comment the line above. This will make everything works properly
}
//print the keys stored by the map (the keys should be printed in increasing order)
map<Pair,int>::iterator it = mapPairInt.begin();
while(it != mapPairInt.end()){
cout<< it->first.a << "-" << it->first.b <<endl;
it++;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你Pair::operator<()
违反了要求std::map
,即及物性.例如,(5,12) < (4,14)
但同时(4,14) < (5,12)
.这必然意味着(5,12) < (5,12)
哪个是错误的(即使它是真的,它也会违反另一个要求,即无反思性).
此违规导致未定义的行为,因此任何事情都可能发生.
BTW是我所知道的最紧凑的正确比较算子的写法
bool operator< (const Pair& otherPair) const {
return std::tie(a, b) < std::tie(otherPair.a, otherPair.b);
}
Run Code Online (Sandbox Code Playgroud)