Is there a prettier syntax for a C ++ iterator?

Is there a more beautiful / less accurate way to use iterators in C ++? From the tutorials I saw, I either set up typedefs everywhere (which makes it tedious to do many one-time for-loops):

typedef std::vector<std:pair<int, int> >::iterator BlahIterator; 

or have a verbose form, for example:

 for (std::vector<std:pair<int, int> >::iterator it = ... ) ... 

Is there a better way?

+6
source share
7 answers

With boost, you can use the FOR_EACH macro.

 typedef pair<int, int> tElem; BOOST_FOREACH( tElem e, aVector ) { cout << e.first << " " << e.second << '\n'; } 
+4
source

In C ++ 11, you can use a range-based loop in combination with the auto keyword:

 for (auto& it : v) ... 
+7
source

Algorithms are sorted by this particular problem.
Especially with the new lambda functions.

 std::for_each(c.begin(), c.end(), Action()); /* Where Action is your functor */ 

Or with lambda:

 std::for_each(c.begin(), c.end(), [](type const& e) { /* Stuff */ }); 

Note: do not fall into the trap of using std :: for_each to replace all loops. There are a number of algorithms that use iterators that allow you to manipulate or perform operations based on the contents of the container.

+2
source

With C ++ 0x, you can use the auto keyword:

 for (auto i = v.begin(); i != v.end(); ++i) {} 
+2
source

I usually use the following naming pattern:

 typedef std::pair<int, int> Blah; typedef std::vector<Blah> Blahs; 

and then use Blahs::iterator , that is, I do not name the iterator, except for the container (and, as a rule, contained in it).
typedef is a very useful abstraction mechanism.

Note that the "Blah" vector is called "Blahs" (i.e. just the plural) and not "BlahVector", because the specific container does not matter.

+1
source

One of the possibilities is to write your own loop (or any other code that uses an iterator), in your own own own general algorithm. Having made it a template, the compiler can / will automatically output the iterator type:

 template <class T> do_something(T begin, T end) { for (T pos = begin; pos != end; ++pos) do_something_with(*pos); } 
0
source

I usually define this, although I was told that I would go to hell:

 #define forsn(i, s, n) for(int i = (s); i < (n); ++i) #define forn(i, n) forsn(i, 0, n) #define forall(it, g) for(typeof g.begin() it = g.begin(); it != g.end(); ++it) 

Then, to iterate over from 0 to n the general problem, I will say forn(i, n) foo(i); and loop any standard container c, say forall(it, c) foo(it); Note that typeof is a GCC extension for the standard.

-1
source

Source: https://habr.com/ru/post/895109/


All Articles