I am trying to create a map using STL C++. But I am getting into problems and am not able to figure out whats exactly is wrong.
For demonstration purposes I put down my code here.
#include <map>
#include <iostream>
using namespace::std;
struct COORD{
int X;
int Y;
bool operator<(const COORD &other) const { return X == other.X && Y == other.Y;}
COORD(int x, int y) {
X = x;
Y = y;
}
};
struct CAR{
double speed;
double model;
double direc;
CAR() {}
CAR(double c1, double c2, double c3) {
speed = c1;
model = c2;
direc = c3;
}
};
int main(int argc, char **argv) {
map <COORD, CAR> p;
p.insert(pair<COORD, CAR>(COORD(20, 20), CAR(10.0, 10.0, 10.0)));
p.insert(pair<COORD, CAR>(COORD(20, 30), CAR(20.0, 10.0, 10.0)));
CAR c1 = p.at(COORD(20, 30));
cout << c1.speed << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
So when you execute the code, the new inserted value is not displayed. Actually if you try to update the old one that also doesn't work. Can anyone let me know whats wrong. Why this is happening?
jua*_*nza 14
Your less-than comparison must implement a strict weak ordering. This is a requirement, without which, the maps cannot work. Your less-than operator does not respect that.
This is an example of a comparison that would work:
#include <tuple> // for std::tie
bool operator<(const COORD &other) const
{
return std::tie(X, Y) < std::tie(other.X, other.Y);
}
Run Code Online (Sandbox Code Playgroud)
where the std::tie
comparison is lexicographical, using X
first, then Y
. I also changed the name of the class to COORD
because __COORD__
is a reserved name.
归档时间: |
|
查看次数: |
936 次 |
最近记录: |