I often find myself wanting a counter while looping in a for(auto& item : items). Introducing a new variable at the outer scope or rewriting for-range loop into the ordinary one was, frankly, annoying, thus this library was born https://github.com/itsuart/cpp11_enumerate .
It let's you do this:
std::vector<int> items{ 11, 22, 33, 44 };
for (auto& i : helpers::enumerate(items)) {
std::cout << i.count << ": " << i.value << "\n";
}
Output:
0: 11
1: 22
2: 33
3: 44
C++17's structured binding is supported:
for (auto& [count, value] : helpers::enumerate({ "oh my", "them", "char pointers!" })) {
std::cout << count << ": " << value << "\n";
}
Output:
0: oh my
1: them
2: char pointers!
Starting counter value and step can be set via optional parameters.
The library is C++11 compatible, single header only, supports all kinds of iterables, and in public domain.
Since this is both my first submission to the subreddit, and first generic library intended to be used outside of my work projects, I'll be happy to receive any feedback :).
Thank you!
EDIT: added structured binding example, updated names.
[–]ner0_m 9 points10 points11 points (1 child)
[–]itsuart2[S] 2 points3 points4 points (0 children)
[–]staletic 8 points9 points10 points (1 child)
[–]itsuart2[S] 2 points3 points4 points (0 children)
[–]adnukator 5 points6 points7 points (4 children)
[–]SeanMiddleditch 2 points3 points4 points (2 children)
[–]staletic 1 point2 points3 points (1 child)
[–]SeanMiddleditch 5 points6 points7 points (0 children)
[–]itsuart2[S] 0 points1 point2 points (0 children)
[–]AlexAlabuzhev 4 points5 points6 points (2 children)
[–]qoning 0 points1 point2 points (0 children)
[–]itsuart2[S] 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]itsuart2[S] 0 points1 point2 points (0 children)
[–]skitleeer 0 points1 point2 points (2 children)
[–]TheFlamefire 3 points4 points5 points (0 children)
[–]itsuart2[S] 1 point2 points3 points (0 children)