1

I have to search a {key, value} pair in a vector<list<pair<int, int>>>. There are 2 ways I tried doing this:

  1. Using an iterator

    list<pair<int, int>> :: iterator search(int key)
     {
         int h = hash_func(key);
         auto itr = v[h].begin();
         while(itr!=v[h].end())
         {
             if(itr->first==key)
                 return itr;
             itr++;
         }
         return itr;
     }
    

    This approach works just fine!

  2. However, I tried another approach - using find() function

    list<pair<int, int>> :: iterator search(int key)
     {
         int h = hash_func(key);
         return find(v[h].begin(), v[h].end(), key);
     }
    

    I'm getting the following error:

error: invalid operands to binary expression ('std::pair<int, int>' and 'const int') { return *__it == _M_value; }

I'm still new to STL and have not been able to figure out where I'm going wrong!

I'm aware that the find function is supposed to return an iterator pointing to a {key, value} pair. The fact that I'm using a list of pair, will I still be needing to update some iterator as I was doing in the 1st approach?

juhikushwah
  • 33
  • 1
  • 8
  • 1
    That question is about `std::set`, not `std::list`, but the answer is the same - you need a lambda to search by specific element of the pair. C++20 ranges could be used to avoid lambda. – Yksisarvinen Apr 28 '22 at 19:05

0 Answers0