【发布时间】:2015-09-18 13:51:52
【问题描述】:
我有一个存储自定义数据的集合,我想通过键值搜索它。
这是一个简单的例子:
struct Data {
Data(int x, int y):x(x), y(y){}
int x;
int y;
};
struct Compare {
bool operator() (const Data& lhs, const Data& rhs) {
return lhs.x < rhs.x;
}
};
int main()
{
set<Data, Compare> s;
s.insert(Data(2, 77));
s.insert(Data(3, 15));
s.insert(Data(1, 36));
for (auto i:s)
cout<<i.x<<" "<<i.y<<endl;
auto i = s.find(3); // <-- Not working
auto i = s.find(Node(3, 0));
if (i != s.end())
cout<<"found"<<endl;
else
cout<<"not found"<<endl;
}
此集合仅按x 排序,但我必须创建一个临时对象以在集合中搜索:s.find(Node(3, 0))
是否可以仅按键搜索?即s.find(3)?
【问题讨论】:
-
你可能想看看
std::map。 -
@n.m.不错,会考虑的