【发布时间】:2015-10-13 14:10:41
【问题描述】:
我有一个简单的地图程序。它需要一个类作为关键。该类有多个成员。我假设我的比较函数是正确的。我遵循严格的弱排序。问题是,它允许输入重复的键。
下面是我的代码。
#include <iostream>
#include <string.h>
#include <map>
class mapkey
{
public:
std::string mInterface;
std::string mDestination;
int mPrefixLen;
std::string mNextHop;
int mMetric;
mapkey() {}
~mapkey() {}
mapkey(std::string a, std::string b, int c, std::string d, int e)
{
mInterface = a;
mDestination = b;
mPrefixLen = c;
mNextHop = d;
mMetric = e;
}
};
struct mapcomp
{
bool operator() (const mapkey left, const mapkey right);
};
bool mapcomp::operator() (const mapkey left, const mapkey right)
{
if(strcmp(left.mInterface.c_str(), right.mInterface.c_str()) < 0)
return true;
if(strcmp(left.mInterface.c_str(), right.mInterface.c_str()) > 0)
return false;
if(strcmp(left.mDestination.c_str(), right.mDestination.c_str()) < 0)
return true;
if(strcmp(left.mDestination.c_str(), right.mDestination.c_str()) > 0)
return false;
if(strcmp(left.mNextHop.c_str(), right.mNextHop.c_str()) < 0)
return true;
if(strcmp(left.mNextHop.c_str(), right.mNextHop.c_str()) > 0)
return false;
if(left.mPrefixLen < right.mPrefixLen)
return true;
if(left.mPrefixLen > right.mPrefixLen)
return false;
if(left.mMetric < right.mMetric)
return true;
if(left.mMetric > right.mMetric)
return false;
}
typedef std::map<mapkey, std::string, mapcomp> script_map;
script_map mm;
void print_map()
{
script_map::const_iterator iter;
for (iter = mm.begin(); iter != mm.end(); iter++)
{
std::cout << "value is - " << iter->second << std::endl;
}
}
int main()
{
mapkey test1("eth1", "50.60.70.80", 1, "90.10.20.30", 1);
mm[test1] = "first";
mapkey test2("eth1", "50.60.70.40", 1, "90.10.20.30", 1);
mm[test2] = "second";
mapkey test3("eth1", "50.60.70.20", 1, "90.10.20.30", 1);
mm[test3] = "third";
mapkey test4("eth1", "50.60.70.80", 1, "90.10.20.30", 1);
mm[test4] = "fourth";
print_map();
return 0;
}
上面的程序,第一个和第四个键是一样的。当我打印地图时,输出如下
g++ --std=c++11 map.cpp
./a.out
值为 - 第三个
值为 - 秒
值是 - 第四
值是 - 第一
我错过了什么?第四个条目应该没有被添加。
【问题讨论】:
-
所以,你的比较函数不正确。
-
所有的 C 函数是什么?
std::string附带built in comparison operators。您可能还想使用std::tie -
你的编译器应该警告你比较可能没有返回值,如果对象相等就会发生这种情况。如果确实如此但您忽略了它,请停止忽略警告。