c 在std :: vector中搜索

C++ search in an std::vector

本文关键字:搜索 vector std      更新时间:2023-10-16

说我有这样的向量:

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

现在,我希望在cont中找到其first等于"ABC"的Elem。如何使用STL为我们提供的函数和算法轻松执行此操作(find_if,is_equal ??)。(请不要提升,也没有新的C 。)

编辑:是否可以在不定义谓词函数的情况下进行?

之类的东西
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))));

如果您需要的速度比O(N)搜索快,则可以替换vector使用map(或平行添加) O(log N)搜索(或使用unordered_mapO(1)),不需要函数:

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库(可耻的插头),这将只是:

#include <sto/sto.h>
using namespace sto;
...
auto it = cont / (_0=="ABC");

此处/ OVERAPARED OP OP,该OP在内部调用find_if;_0-引用Sto Lambda表达式中元素(或对)的第一个元素;_0=="ABC" -LAMBDA表达式生成find_if

的谓词