简体   繁体   中英

Find pair by key within a vector of pairs in C++ 98

I am using the below version and will not be able to use C++11 g++ (SUSE Linux) 4.3.4 [gcc-4_3-branch revision 152973].

I have a vector of pairs.

  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")));

now I can use iterator to search all the elements in the vector using a key of the pair, like

    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;
      }
    }

I wish is there any possible way to use std::find operations in C++98 , as I have searched related posts and most of them solved that which is supported in C++ 11.

C++11 just makes the code more succinct. In C++11, we might write:

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

Now, in C++98, that lambda is going to be more verbose:

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));    

Classes like SearchFunction are often referred to as Functors .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM