【问题标题】:C++ search in an std::vectorC++ 在 std::vector 中搜索
【发布时间】:2012-12-24 08:55:14
【问题描述】:

假设我有一个这样的向量:

vector< pair<string, pair<int, int> > > cont;

现在我想在cont 中找到其first 等于"ABC" 的元素。如何使用 STL 提供给我们的函子和算法(find_if、is_equal??)轻松做到这一点。 (请不要使用 Boost,也不要使用新的 C++。)

编辑:是否可以不定义谓词函子?

【问题讨论】:

  • 你自己说的:std::find_if。您也可以将其与 lambda 结合使用。
  • 很遗憾被锁定在 C++11 和 boost 之类的伟大事物之外:(

标签: c++ stl vector find


【解决方案1】:

类似

typedef std::pair<std::string, std::pair<int, int> > pair_t;

struct Predicate : public std::unary_function<pair_t, bool>
{
public:
   Predicate(const std::string& s):value(s) { }
   result_type operator () (const argument_type& pair)
   {
      return pair.first == value;
   }
private:
   std::string value;
};

std::vector<pair_t>::const_iterator pos = std::find_if(cont.begin(), cont.end(),
Predicate("ABC"));

或 lambda,如果是 C++11。

auto pos = std::find_if(cont.begin(), cont.end(),
[](const std::pair<std::string, std::pair<int, int>>& pair)
{
    return pair.first == "ABC";
});

真的,有一种不好的方法来做这样的事情,没有结构。

typedef std::pair<std::string, std::pair<int, int> > pair_t;

namespace std {
template<>
bool operator ==<> (const pair_t& first, const pair_t& second)
{
   return first.first == second.first;
}
}

std::vector<pair_t>::const_iterator pos = std::find_if(cont.begin(), cont.end(),
std::bind2nd(std::equal_to<pair_t>(), std::make_pair("ABC", std::make_pair(1, 2))));

【讨论】:

  • 请使用旧标准?
  • 感谢您提供出色的解决方案。是否可以在不定义谓词的情况下做同样的事情?
  • @Narek std::bind2nd 仅适用于可调用对象,不能适用于函数(也适用于由 ptr_fun 创建的仿函数)。 equal_to 使用运算符 ==,因此在这种情况下您需要重载。
【解决方案2】:

如果需要比O(N)更快的搜索,可以替换vector 使用map(或添加并行)进行O(log N) 搜索(或O(1) 使用unordered_map),不需要仿函数:

vector<pair<string, pair<int,int>>>  cont {{"ABC",{1,11}}, {"DFG",{2,22}}};
map        <string, pair<int,int>>   M(cont.begin(), cont.end());
cout << M["ABC"] << endl;

使用RO library(可耻的插件),这将是:

#include <sto/sto.h>
using namespace sto;

...
auto it = cont / (_0=="ABC");

这里/重载了内部调用find_if的操作; _0 - 在 STO lambda 表达式中引用元组(或对)的第一个元素; _0=="ABC" - 为 find_if 生成谓词的 lambda 表达式

【讨论】:

  • 无序数据结构可能比有序数据结构慢,另一方面,它取决于向量及其对内存中连续分配的授权,有时可能非常昂贵。跨度>
猜你喜欢
  • 1970-01-01
  • 2011-12-28
  • 2022-01-03
  • 2011-01-01
  • 2011-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多