Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

range-based for in c++11

in c++ 11 if we have a set<int> S; we could say:

for (auto i: S)
    cout << i << endl;

but can we force i to be a iterator, I mean write a code that is equivalent to:

for (auto i = S.begin(); i != S.end(); i++)
    cout << (i != s.begin()) ? " " : "" << *i;

or could we do something that we can understand the index of i in the set(or vector)?

and another question is how could we say that don't do this for all elements in S but for first half of them or all of them except the first one.

or when we have a vector<int> V, and want to print its first n values what should we do? I know we can create a new vector but it takes time to copy a vector to a new vector.

like image 973
Farzam Avatar asked Jan 25 '12 16:01

Farzam


People also ask

When can you use range-based for loop C++?

Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .

What is use of auto in for loop?

Range-based for loop in C++ Often the auto keyword is used to automatically identify the type of elements in range-expression. range-expression − any expression used to represent a sequence of elements.


1 Answers

Range-based for is intended for simple cases. I'd expect to to mildly useful while protoyping something but would expect uses of it mostly gone long before things actually become a product. It may possibly useful to make life for beginners easier, but this is an area I can't judge (but what seems to drive a lot of the recent C++ discussions).

The only somewhat constructive approach could be to use an adapter which references the underlying range and whose begin() and end() methods adjust the iterator appropriately. Also note that you probably want to hoist any special handling of the first or last element out of the loop processing the bulk of the data. Sure, it is only another check followed by a correctly predicted branch vs. no check and less pollution of the branch prediction tables.

like image 152
Dietmar Kühl Avatar answered Oct 01 '22 00:10

Dietmar Kühl