How could I detect the last iteration of a map using structured bindings?
Here's a concrete example: I have the following simple code whereby I print elements from an std::map
using structured bindings from C++17:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, size_t> mymap {{"a", 0}, {"b", 1}, {"c", 2}, {"d", 3}};
// using structured bindings, C++17
for (auto const& [key, value] : mymap) {
std::cout << "key: " << key << ", value: " << value << ", ";
}
return 0;
}
The problem is, this will result in a trailing comma, i.e.
key: a, value: 0, key: b, value: 1, key: c, value: 2, key: d, value: 3,
Inspired by this question: How can I detect the last iteration in a loop over std::map?, I can write code with an iterator to print out the std::map
contents without the trailing comma, i.e.
for (auto iter = mymap.begin(); iter != mymap.end(); ++iter){
// detect final element
auto last_iteration = (--mymap.end());
if (iter==last_iteration) {
std::cout << "\"" << iter->first << "\": " << iter->second;
} else {
std::cout << "\"" << iter->first << "\": " << iter->second << ", ";
}
}
How does one do this with for (auto const& [key, value] : mymap)
? If I know the final key in std::map
, I could write an conditional for it; but is there another way without resorting to iter
?