Ser*_*gio 2 c++ c++11 c++14 c++17
How can I print a range of elements (key and value) belonging to a std::map<size_t, std::string>?
I don't need to print all elements.
Every suggestion using C++11, C++14 or C++17, without boost libraries, is appreciated.
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
using namespace std;
void print(map<size_t, string> & m)
{
for(auto & [key, value] : m)
{
cout << setw(6) << left << key << value << endl;
}
}
void print_range(map<size_t, string> & m, size_t first, size_t last)
{
// ???
}
int main()
{
map<size_t, string> data {
{ 5, "guitar" },
{ 8, "saxophone" },
{ 28, "trumpet" },
{ 32, "trombone" },
{ 42, "violin" },
{ 45, "viola" },
{ 48, "cello" },
{ 52, "double bass" },
{ 100, "piano" },
{ 104, "drum" }
};
print(data);
print_range(data, 42, 52); // ???
return 0;
}
Run Code Online (Sandbox Code Playgroud)
The expected output is:
42 violin
45 viola
48 cello
52 double bass
Run Code Online (Sandbox Code Playgroud)
Use std::map::lower_bound() and std::map::upper_bound()
auto p = make_pair(data.lower_bound(42), data.upper_bound(52));
for (auto [begin, end] = p; begin != end; begin++) {
std::cout << begin->first << " " << begin->second << '\n';
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
114 次 |
| 最近记录: |