c++ - How to find all keys in map in C++11 which are equal or higher than KEY_1 and lower than KEY_2? -



c++ - How to find all keys in map in C++11 which are equal or higher than KEY_1 and lower than KEY_2? -

how find keys in map in c++11 equal or higher key_1 , lower key_2?

i programme in java , don't have much experience in c++.

try following

auto minmax = std::minmax( key_1, key_2, m.key_comp() ); auto first = m.lower_bound( minmax.first ); auto lastly = m.upper_bound( minmax.second );

here demonstrative program:

#include <iostream> #include <map> #include <algorithm> int main() { std::map<int, int> m = { { 1, 10 }, { 2, 20 }, { 3, 30 }, {4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 } }; int key1 = 5; int key2 = 3; auto minmax = std::minmax( key1, key2, m.key_comp() ); auto first = m.lower_bound( minmax.first ); auto lastly = m.upper_bound( minmax.second ); ( auto current = first; current != last; ++current ) { std::cout << "{ " << current->first << ", " << current->second << " }" << std::endl; } homecoming 0; }

the output is

{ 3, 30 } { 4, 40 } { 5, 50 }

or more interesting example

#include <iostream> #include <map> #include <algorithm> #include <functional> int main() { std::map<int, int> m1 = { { 1, 10 }, { 2, 20 }, { 3, 30 }, { 4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 } }; int key1 = 5; int key2 = 3; auto minmax1 = std::minmax( key1, key2, m1.key_comp() ); auto first1 = m1.lower_bound( minmax1.first ); auto last1 = m1.upper_bound( minmax1.second ); ( auto current = first1; current != last1; ++current ) { std::cout << "{ " << current->first << ", " << current->second << " }" << std::endl; } std::cout << std::endl; std::map<int, int, std::greater<int>> m2 = { { 1, 10 }, { 2, 20 }, { 3, 30 }, { 4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 } }; auto minmax2 = std::minmax( key1, key2, m2.key_comp() ); auto first2 = m2.lower_bound( minmax2.first ); auto last2 = m2.upper_bound( minmax2.second ); ( auto current = first2; current != last2; ++current ) { std::cout << "{ " << current->first << ", " << current->second << " }" << std::endl; } homecoming 0; }

the output is

{ 3, 30 } { 4, 40 } { 5, 50 } { 5, 50 } { 4, 40 } { 3, 30 }

if want exclude upper bound range have substitute phone call of method upper_bound lower_bound code contain 2 calls of lower_bound corresponding keys. example

auto first1 = m1.lower_bound( minmax1.first ); auto last1 = m1.lower_bound( minmax1.second );

if want exclude lower bound range can write

auto first1 = m1.upper_bound( minmax1.first ); auto last1 = m1.upper_bound( minmax1.second );

c++ c++11

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -