在 C++ 98 中的对向量中按键查找对

Dip*_*jan 0 c++ vector

我正在使用以下版本,将无法使用 C++11 g++ (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973]。

我有一个成对的向量。

  std::vector<std::pair<int, std::string> > vec;
  vec.push_back(std::make_pair(5, std::string("tata")));
  vec.push_back(std::make_pair(6, std::string("tat2")));
  vec.push_back(std::make_pair(7, std::string("tat3")));
  vec.push_back(std::make_pair(8, std::string("tat4")));
Run Code Online (Sandbox Code Playgroud)

现在我可以使用迭代器使用该对的键搜索向量中的所有元素,例如

    std::vector<std::pair<int, std::string> >:: iterator it ;
    for (it = vec.begin(); it != vec.end(); ++it)
    {
      if (it->first == item)
      {
        cout << "Found " << item << "\n";
        return 0;
      }
    }
Run Code Online (Sandbox Code Playgroud)

我希望有任何可能的方法在 C++98 中使用 std::find 操作,因为我已经搜索了相关的帖子,其中大多数都解决了 C++ 11 支持的问题。

Bil*_*nch 5

C++11 只是让代码更简洁。在 C++11 中,我们可以这样写:

std::find_if(vec.begin(), vec.end(), [&](std::pair<int, std::string> const & ref) {
    return ref.first == item;
});
Run Code Online (Sandbox Code Playgroud)

现在,在 C++98 中,该 lambda 将变得更加冗长:

class SearchFunction {
    public:
        SearchFunction(int item): item_(item) {}
        bool operator()(std::pair<int, std::string> const & ref) {
            return ref.first == item_;
        }
    private:
        int item_;
};

std::find_if(vec.begin(), vec.end(), SearchFunction(item));    
Run Code Online (Sandbox Code Playgroud)

像这样SearchFunction的类通常被称为Functors