假设我有一个(填充)列表
std::list<std::pair<int,otherobject>> myList;
并希望 find() 此列表中的第一个元素,其中 int 具有特定值 - 我该怎么做?
进一步解释一下:
我想将这些对附加到列表中,并带有一个标识其他对象但不是唯一的 int。必须保持这些 int/otherobject 对到达的顺序。
在访问此列表的元素期间发现 int 时,必须返回(并删除)该 int 的第一次出现。
谢谢!
我想我会使用标准find_if
算法:
auto pos = std::find_if(myList.begin(), myList.end(),
[value](std::pair<int, otherobject> const &b) {
return b.first == value;
});
这为具有所需值的元素提供了一个迭代器——从那里,您可以复制值、删除值等,就像使用任何其他迭代器一样。
根据您的需要,更好的选择是使用多图。在你的情况下,它会给:
std::multimap<int, otherobject> myMultiMap;
然后在寻找与 int (myInt) 链接的其他对象时,您将执行以下操作:
std::pair<std::multimap<int, otherobject>::iterator, std::multimap<int, otherobject>::iterator> result = myMultiMap.equal_range(myInt);
for (std::multimap<int,otherobject>::iterator iter=result.first; iter!=result.second; ++iter)
{
std::cout << it->second;
}
这是一个 STL 容器,因此您可以轻松找到在线文档。