in c++11, if I use a range based for loop on vector, will it guarantee the iterating order? say, will the following code blocks are guaranteed for same output?
Yes and no (It depends on the container in use):
Example:
#include <iostream>
#include <map>
int main()
{
typedef std::map<int, int> map;
map m = { { 0, 0 }, { 2, 2 }, { 4, 4 } };
for(const auto& e : m) {
std::cout << e.first << " ";
}
std::cout << std::endl;
for(map::size_type i = 0; i < m.size(); ++i) {
std::cout << m[i] << " ";
}
std::cout << std::endl;
return 0;
}
The result is:
0 2 4
0 0 2 0 4
(The second result might be a good shot in the own foot or even intended)
Yes, they are equivalent. The standard guarantees in 6.5.4:
For a range-based for statement of the form
for ( for-range-declaration : expression ) statementlet
range-initbe equivalent to the expression surrounded by parentheses ( expression )and for a range-based for statement of the form
for ( for-range-declaration : braced-init-list ) statementlet
range-initbe equivalent to the braced-init-list. In each case, a range-based for statement is equivalent to
{
auto && __range = range-init;
for ( auto __begin = begin-expr,
__end = end-expr;
__begin != __end;
++__begin ) {
for-range-declaration = *__begin;
statement
}
}
where
__range,__begin, and__endare variables defined for exposition only, and_RangeTis the type of the expression, andbegin-exprandend-exprare determined as follows:— if
_RangeTis an array type,begin-exprandend-exprare__rangeand__range + __bound, respectively, where__boundis the array bound. If_RangeTis an array of unknown size or an array of incomplete type, the program is ill-formed;— if
_RangeTis a class type, the unqualified-idsbeginandendare looked up in the scope of class_RangeTas if by class member access lookup (3.4.5), and if either (or both) finds at least one declaration,begin-exprandend-exprare__range.begin()and__range.end(), respectively;— otherwise,
begin-exprandend-exprarebegin(__range)andend(__range), respectively, wherebeginandendare looked up with argument-dependent lookup (3.4.2). For the purposes of this name lookup, namespacestdis an associated namespace.
Though your question about map is a bit nonsensical. If it's an ordered map and you iterate through the map properly, then they're equivalent. If it's an unordered map then your question doesn't really make much sense.
Yes the two codes are guaranteed to do the same. Though I don't have a link to the standard you can have a look here. I quote: You can read that as "for all x in v" going through starting with v.begin() and iterating to v.end().