ranged-loops

How to simplify the adapter scheme?

折月煮酒 提交于 2020-05-15 19:37:06
问题 To make it clear, I post the code of "how to use" first: AB.h: #include <vector> #include <list> // execpt they both have children, A & B share nothing in common, // even children use different containers struct A { int num; std::vector<A> children; }; struct B { std::string s; float n; std::list<B> children; }; main.cpp: #include "Node.h" // handle A & B with the common interface Node // do not use template, since in practice, print() may be a large library void print(Node& n) { printf("%s\n

Wrap iteration handle for use in range-based for-loops

爷,独闯天下 提交于 2019-12-23 19:34:05
问题 I use an API that comes with an iteration functionality using a void* handle. void* handle = BrowseInit(); while (BrowseGetNext(handle)) { // ... int x = BrowseGetData(handle); } BrowseFree(handle); How would I go about wrapping this into a C++11 iterator for use in range-based for-loops? Since the value of the handle doesn't actually change, I need some trickery in operator != () . class Iterator { public: friend class it; class it { public: it(Iterator* data) : _data(data) { } bool operator

Obtaining item index in ranged based for on vector

耗尽温柔 提交于 2019-11-28 13:19:52
The C++11 introduced ranged-based for loop that is internally implemented using (const) iterators so this: std::vector<std::string> vec; for(std::string &str : vec) { //... } is basically equivalent to more verbose (yes, it could be simplified using auto ): for(std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); ++it) { //... } However commonly one needs an index of the item as well. With the second approach that is easy: auto index = it - vec.begin(); In ranged-based for it is not so straightforward. But I was wondering if this was ok and portable solution that avoids

Obtaining item index in ranged based for on vector

大兔子大兔子 提交于 2019-11-27 07:37:06
问题 The C++11 introduced ranged-based for loop that is internally implemented using (const) iterators so this: std::vector<std::string> vec; for(std::string &str : vec) { //... } is basically equivalent to more verbose (yes, it could be simplified using auto ): for(std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); ++it) { //... } However commonly one needs an index of the item as well. With the second approach that is easy: auto index = it - vec.begin(); In ranged-based for it

C++11 reverse range-based for-loop

旧时模样 提交于 2019-11-26 02:27:03
问题 Is there a container adapter that would reverse the direction of iterators so I can iterate over a container in reverse with range-based for-loop? With explicit iterators I would convert this: for (auto i = c.begin(); i != c.end(); ++i) { ... into this: for (auto i = c.rbegin(); i != c.rend(); ++i) { ... I want to convert this: for (auto& i: c) { ... to this: for (auto& i: std::magic_reverse_adapter(c)) { ... Is there such a thing or do I have to write it myself? 回答1: Actually Boost does have