0

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.

Dipanjan
  • 181
  • 3
  • 12

1 Answers1

5

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.

Community
  • 1
  • 1
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • Thanks Bill. One more follow up question. which out the two way is faster compare to the other ?? which one is preferred where speed is an constraint ? – Dipanjan Feb 03 '16 at 06:23
  • IMHO, the compiler should eventually generate similar assembly code for the two versions. The difference is only on *how* you tell the compiler to do that. But it might be worth profiling that... – kebs Feb 03 '16 at 08:41