Search code examples
c++searchstlstl-algorithm

Search variable/item/attribute using STL in c++?


There is any way to search an item or attribute or variable in C++ using STL .
We can use any container of STL providing Searching time as less as possible . Container contains pair<int,int> . i would like to search a pair p(a,x) which should return all pairs X whose p.first == Xi.first and p.second != Xi.second for all i .
e.g.
Let container is unordered_set .

  unordered_set< pair<int , int > > myset =
  {{1,2},{1,5},{1,6},{2,4},{3,5},{4,6},{6,7},{6,8}};
  if i search for p(1,5) then it should return pair(1,2),(1,6)
  if i search for p(2,4) or (3,5),(6,7) then it should return NULL i.e. nothing
  if i search for p(6,7) then it should return pair(6,8)

Solution

  • Something along the lines of

    std::vector<std::pair<int, int>> 
      find_nonmatching_values(const std::unordered_multimap<int, int> & thing,
                              int key, int value) {
        std::vector<std::pair<int, int>> ret;
        auto range = thing.equal_range(key);
        std::copy_if(range.first, range.second, std::back_inserter(ret),
                     [value](const std::pair<const int, int> &p) 
                     { return p.second != value; });
        return ret;
    }
    

    Demo. Templatizing this code is left as an exercise for the reader.