【发布时间】:2012-01-07 17:33:21
【问题描述】:
我有一个以struct 作为键的映射,我重载了< 运算符,但映射将每个条目存储为单独的键,即使它们相同。代码如下:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
struct vertex
{
int color;
vertex *pi;
int index;
bool operator<(const vertex & v ) const {
return this->index < v.index;
}
bool operator==(const vertex & v) const {
return this->index == v.index;
}
};
int main()
{
int x, y, num_edges;
vector<vertex* > v;
vertex *temp1, *temp2, *temp;
map<vertex*, vector<vertex*> > m;
map<vertex*, vector<vertex*> >::iterator it;
cout << "\nEnter no. of edges: ";
cin >> num_edges;
for( int i = 0; i < num_edges; i++ )
{
cout << "\nEnter source: ";
cin >> x;
cout << "\nEnter dest: ";
cin >> y;
temp1 = new vertex;
temp2 = new vertex;
temp1->index = x;
temp2->index = y;
m[temp1].push_back(temp2);
m[temp2].push_back(temp1);
}
temp1 = new vertex;
temp2 = new vertex;
cout << "\nPrinting map: " << endl;
for( it = m.begin(); it != m.end(); it++ )
{
temp = (*it).first;
cout << temp->index << "\t";
v = (*it).second;
for( int i = 0; i < v.size(); i++ )
{
temp1 = v[i];
cout << temp1->index << "\t";
}
cout << "\n";
v.clear();
}
for( it = m.begin(); it != m.end(); it++ )
{
temp = (*it).first;
v.push_back(temp);
}
return 0;
}
我现在得到的输出是:
Enter no. of edges: 4
Enter source: 1
Enter dest: 3
Enter source: 4
Enter dest: 3
Enter source: 4
Enter dest: 2
Enter source: 2
Enter dest: 1
Printing map:
1 3
3 1
4 3
3 4
4 2
2 4
2 1
1 2
但应该是:
1 3 2
2 4 1
3 1 4
4 3 2
我哪里错了?
【问题讨论】:
标签: c++ dictionary struct key stdmap