map<vector<int>, string> M; M.find(...) 

If the search is performed by key, then how can I search, if for example I want to search for 1 element of the vector or even how to search for elements if the associative matrix has a key like some container like a display?

  • Do you want to sort the map by comparing the first elements of the vectors or by comparing the vectors themselves, and search for the first element of the vectors? - Vlad from Moscow
  • Well, for example, the predicate compares the elements of the vector - STC
  • The vector <is already defined for the vector. - Vlad from Moscow

1 answer 1

If I understand you correctly, you can use the lower_bound or equal_range method to find the elements in std::map by the first element in the vector. Otherwise, if you want to search for an element in a vector other than the first, then you will have to std::find_if through the elements, using, for example, the standard algorithm std::find_if .

For example,

 #include <iostream> #include <map> #include <vector> #include <string> #include <algorithm> int main() { std::map<std::vector<int>, std::string> m = { { { 1, 3, 5 }, "A" }, { { 2, 4, 6 }, "B" }, { { 3, 5, 7 }, "C" }, { { 4, 6, 8 }, "D" } }; int value = 3; auto it = m.lower_bound( { value } ); if ( it != m.end() ) { std::cout << it->second << ": "; for ( auto x : it->first ) std::cout << x << ' '; std::cout << std::endl; } value = 3; std::vector<int>::size_type n = 1; it = std::find_if( m.begin(), m.end(), [&]( const std::pair<const std::vector<int>, std::string> &p ) { return ( n < p.first.size() ) and ( p.first[n] == value ); } ); if ( it != m.end() ) { std::cout << it->second << ": "; for ( auto x : it->first ) std::cout << x << ' '; std::cout << std::endl; } return 0; } 

The output of the program is the following

 C: 3 5 7 A: 1 3 5 
  • I wrote in general: “for example, I want to search for 1 element”, but if I want to search for 2,3, 50 ... what should I do? - STC
  • @STC Then you have to perform a sequential search, for example, using the standard algorithm std :: find_if. - Vlad from Moscow
  • @STC See my updated answer. - Vlad from Moscow