2014-11-15 40 views
0

当我使用operator []在C++ map中插入元素时,会发生错误。运算符[]和insert()函数不应该在C++映射中表现相同的方式吗?

我有这张地图< Pair,int> variable。当我向其中插入一个新元素,然后使用迭代器打印其键时,地图的某些元素会随机消失,并且值不会按递增顺序打印。但是,当我使用funtion insert()插入元素时,一切正常。我在做运营商[]做错了什么?两种情况下的结果都不应该相同吗?

备注:每个键对都是一个存储一对整数的结构。

这是一个例子: 我插入了六个以下的键(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; 
} 

回答

5

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); 
} 
0
bool operator<(const Pair& otherPair) const { 
    if (this->a == otherPair.a) 
    { 
     return this->b < otherPair.b; 
    } 
    return this->a < otherPair.a; 
} 

是您的比较应该是什么样子。它产生你期望的结果。

相关问题