我正在尝试以我的结构
Tenor
作为键创建一个有序映射。有序映射需要 operator<
,所以我为我的结构定义它(目前只是一个 占位符,总是返回 true
- 这似乎会导致问题 Q1)。在此示例中,我插入了 3 个元素。但是,按照下面的示例,当我迭代地图时,它只迭代 2 个元素,而不是 3 个。
#include <iostream>
#include <map>
using namespace std;
struct Tenor {
public:
string _label;
Tenor(string label = "3M")
{
_label = label;
}
// Placeholder for now
bool operator<(Tenor const& obj) const
{
return true;
}
};
void tenor_operator_ordered() {
auto t1 = Tenor {"1M"};
auto t2 = Tenor {"2M"};
auto t3 = Tenor {"3M"};
map<Tenor, int> mp;
mp[t1] = 1; //insert
mp[t3] = 3;
mp[t2] = 2;
// Check if items are available?
int item;
item = mp.find(t1)->second;
std::cout << item << '\n';
item = mp.find(t2)->second;
std::cout << item << '\n';
item = mp.find(t3)->second;
std::cout << item << '\n';
cout << "Size: " << mp.size() << endl;
// Printing Test objects in sorted order
for (auto x : mp)
cout << x.first._label << " " << x.second << endl;
}
我的输出:
469761104
469761104
469761104
Size: 3
3M 3
1M 1
问题1:为什么for循环只迭代2个元素?
问题2:为什么
item
不是地图的值(对于每个给定的Key)?
更新 1:感谢评论,看来我的 placeholder 不合适,并且破坏了地图算法。
正如评论所解释的,使用任意
operator<
不遵循严格的弱顺序是错误。运算符重载必须确保 if aa.否则它是未定义的行为。