【发布时间】:2011-09-07 16:34:01
【问题描述】:
我有一个 stl::map 将键定义为我定义的对象,并且 int.地图的使用如下: 我有一个特定对象的列表,我想计算我有多少相同的对象。所以我将对象插入到地图中。如果对象已经存在于地图中,我会增加它的值(因此是计数器)。该对象定义了所有基本运算符。该对象由 5 个字符串组成。 == 运算符定义为所有 5 个字符串的比较,并且在逻辑上在上下文中是有意义的。问题是运算符
class Example
{
private:
string one;
string two;
string three;
string four;
string five;
public:
inline Example (string a_one,string a_two, string a_four, string a_five) :
one(a_one),two(a_two),three(a_three),four(a_four),five(a_five)
{}
inline bool operator == (const Example& other) const
{
if (one == other.one)
{
if (two == other.two)
{
if (three == other.three)
{
if (four == other.four)
{
if (five == other.five)
{
return true;
}
}
}
}
}
return false;
}
inline bool operator < (const Example& other) const
{
if (one < other.one)
{
return true;
}
else if (two < other.two)
{
return true;
}
else if (three < other.three)
{
return true ;
}
else if (four < other.four)
{
return true;
}
else if (five < other.five)
{
return true;
}
else
{
return false;
}
}
}
void CountExample(Example& example,std::map<Example,int>& counters);
void main()
{
std::map<Example,int> counters;
std::list<Example> examples = GetExamples();
//GetExamples defined elsewhere, and initializes examples with a long list of instances of Example
std::list<Example>::const_iterator Iter;
for (Iter = examples.begin();Iter != examples.end();Iter++)
{
CountExample(*Iter);
}
PrintCounters(counters);//PrintCounters defined elsewhere and prints the map to a file
}
void CountExample(Example& example,std::map<Example,int>& counters)
{
std::map<Example,int>::const_iterator Iter;
Iter = counters.find(example);
if (Iter ==counters.end()) //means the specific Example is not in the map
{
counters.insert(std::pair<Example,int>(example,1));
}
else
{
counters[example] += 1;
{
}
【问题讨论】:
-
与其试图描述您的代码,不如发布一些实际代码。
-
我真的很想链接到这个:programmers.stackexchange.com/q/106202/1850
标签: c++ string stl map operator-overloading