9/17/2023 0 Comments Kotlin for each with indexI am currently defending the third place on the top users list of the Kotlin tag on StackOverflow, and I wanted to make use of the bragging rights this gives me while I can. The existence of this feature or lack thereof is the subject of recurring stackoverflow questions.This content was originally published as a series of articles on (with some runnable code snippets!). This feature exists in some form in Python, Rust, Go (backed into the language), and in many C++ libraries: ranges-v3, folly, boost::ranges ( indexed). We propose a view enumerate whose value type is a struct with 2 members index and value representing respectively the position and value of the elements in the adapted range. for (auto = std::tuple įor (auto = its_and_idx(foo) it != end ++it, ++i)Ĭ++ Standard proposal P2164 proposes to add views::enumerate, which would provide a view of a range giving both reference-to-element and index-of-element to a user iterating it. and than other solutions that require a counter with scope outside the for loop. Std::cout << x.index << ": " << x.item << std::endl Ĭ++17 and structured bindings makes this look OK - certainly better than some ugly mutable lambda with a local (Element&) mutable or whatever I've done before admitting that probably not everything should be shoehorned into for_each() et al. A templated free function allows you to create the wrapper class Iterator(typename T::iterator _it, size_t counter=0) : Custom iterator with minimal interface is what you will get inside of the for loop The return value of the operator* of the iterator, this Below is a very minimal exemplary implementation to illustrate the idea: // Distributed under the terms of the GPLv2 or newer The idea behind is, that you build a wrapper struct with a custom iterator that does the counting. A good implementation of the feature you are requested can be found here:
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |