c++11 : range-based for loop
0. 形式
for ( declaration : expression ) statement
0.1 根据标准将会扩展成这样的形式:
1 {
2 auto&& __range = expression;
3 for (auto __begin = begin-expression,
4 __end = end-expression;
5 __begin != __end;
6 ++__begin)
7 {
8 declaration = *__begin;
9 statement
10 }
11 }
0.1.1 行3,4 ,begin 和 end 的判断规则:
The begin-expression and end-expression (lines 3 and 4) are determined as follows:
- A. If expression is an array, then begin-expression and end-expressionare
__rangeand__range + __bound, respectively, where__boundis the array bound. - B. If expression is of a class type that declares
begin()andend()member functions, then begin-expression and end-expression are__range.begin()and__range.end(), respectively. - C. Otherwise, begin-expression and end-expression are
begin(__range)andend(__range), respectively, where thebegin()andend()functions are looked up using the argument-dependent lookup (ADL) which also includes thestdnamespace.
With arrays taken care of by the first rule, the second rule makes sure that all the standard containers as well as all the user-defined ones that follow the standard sequence interface will work with range-based for out of the box. For example, in ODB (an ORM for C++), we have the container-like result class template which allows iteration over the query result. Because it has the standard sequence interface with a forward iterator, we didn’t have to do anything extra to make it work with range-based for.
The last rule (the fallback to the free-standing begin()and end()functions) allows us to non-invasively adapt an existing container to the range-based for loop interface.
0.2 类型推断
std::vector<int> v = {1, 2, 3, 5, 7, 11};
const std::vector<int> cv = {1, 2, 3, 5, 7, 11};
for (auto x: v) // x is int
...;
for (auto x: cv) // x is int
...;
for (auto& x: v) // x is int&
...;
for (auto& x: cv) // x is const int&
1. 例子
- #include <iostream>
- #include <vector>
- int main ()
- {
- std::vector<int> data = { 1, 2, 3, 4 };
- for ( int datum : data )
- {
- std::cout << datum << std::endl;
- }
- }
- /*output
- 1
- 2
- 3
- 4
- */
2. 性能上的考虑
2.1 每次循环会创建一份 a 的拷贝
for(autoa : a_vec){}
2.2 避免拷贝
for(constauto&a : a_vec){}
3. 一个实现了 container semantics 的例子:
3.1 simple iterator
- #include <iostream>
- using namespace std;
- // forward-declaration to allow use in Iter
- class IntVector;
- class Iter
- {
- public:
- Iter(const IntVector* p_vec, int pos)
- : _pos(pos)
- , _p_vec(p_vec)
- { }
- // these three methods form the basis of an iterator for use with
- // a range-based for loop
- bool
- operator!= (const Iter& other) const
- {
- return _pos != other._pos;
- }
- // this method must be defined after the definition of IntVector
- // since it needs to use it
- int operator* () const;
- const Iter& operator++ ()
- {
- ++_pos;
- // although not strictly necessary for a range-based for loop
- // following the normal convention of returning a value from
- // operator++ is a good idea.
- return *this;
- }
- private:
- int _pos;
- const IntVector *_p_vec;
- };
- class IntVector
- {
- public:
- IntVector()
- {
- }
- int get(int col) const
- {
- return _data[col];
- }
- Iter begin() const
- {
- return Iter(this, 0);
- }
- Iter end() const
- {
- return Iter(this, 100);
- }
- void set(int index, int val)
- {
- _data[index] = val;
- }
- private:
- int _data[100];
- };
- int
- Iter::operator* () const
- {
- return _p_vec->get(_pos);
- }
- // sample usage of the range-based for loop on IntVector
- int main()
- {
- IntVector v;
- for (int i = 0; i < 100; i++)
- {
- v.set(i, i);
- }
- for (int i : v) { cout << i << endl; }
- }
3.2 reverse iterator
template <typename T>
struct reverse_range
{
private:
T& x_;
public:
reverse_range (T& x): x_ (x) {}
auto begin () const -> decltype (this->x_.rbegin ())
{
return x_.rbegin ();
}
auto end () const -> decltype (this->x_.rend ())
{
return x_.rend ();
}
};
template <typename T>
reverse_range<T> reverse_iterate (T& x)
{
return reverse_range<T> (x);
}
std::vector<int> v = {1, 2, 3, 5, 7, 11};
for (auto x: reverse_iterate (v))
4. 一个完整的例子 (编译出错,说找不到容器 begin end 实现)
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <iterator>
- #include <algorithm>
- #include <unordered_map>
- template<classITERATOR>
- ITERATOR begin( std::pair<ITERATOR,ITERATOR> &range )
- {
- returnrange.first;
- }
- template<classITERATOR>
- ITERATOR end( std::pair<ITERATOR,ITERATOR> &range )
- {
- returnrange.second;
- }
- template<classT>
- std::istream_iterator<T> begin(std::istream_iterator<T> &ii_stream)
- {
- returnii_stream;
- }
- template<classT>
- std::istream_iterator<T> end(std::istream_iterator<T> &ii_stream)
- {
- returnstd::istream_iterator<T>();
- }
- intmain(intargc, char* argv[])
- {
- std::ifstream data( "sowpods.txt");
- std::unordered_map<std::string,int> counts;
- std::unordered_multimap<std::string,std::string> words;
- for( conststd::string &s : std::istream_iterator<std::string>( data ) )
- {
- std::string temp = s;
- std::sort(temp.begin(), temp.end() );
- counts[temp]++;
- words.insert( std::make_pair(temp,s) );
- }
- auto ii = std::max_element( counts.begin(),
- counts.end(),
- [](conststd::pair<std::string,int> &v1,
- conststd::pair<std::string,int> &v2)
- {
- returnv1.second < v2.second;
- }
- );
- std::cout << "The maximum anagram family has " << ii->second << " members:\n";
- for( constauto &map_entry : words.equal_range( ii->first ) )
- std::cout << map_entry.second << " ";
- std::cout << std::endl;
- return0;
- }
//z 2014-06-12 13:26:11 L.202'38029 BG57IV3@XCL T2508411853.K.F636940351 [T11,L175,R6,V152]
5. 一些 wrapper 或 iterator 例子
#include <memory>
#include <iterator>
/* Only provides the bare minimum to support range-based for loops.
Since the internal iterator of a range-based for is inaccessible,
there is no point in more functionality here. */
template< typename iter >
struct range_iterator_reference_wrapper
: std::reference_wrapper< iter > {
iter &operator++() { return ++ this->get(); }
decltype( * std::declval< iter >() ) operator*() { return * this->get(); }
range_iterator_reference_wrapper( iter &in )
: std::reference_wrapper< iter >( in ) {}
friend bool operator!= ( range_iterator_reference_wrapper const &l,
range_iterator_reference_wrapper const &r )
{ return l.get() != r.get(); }
};
namespace unpolluted {
/* Cannot call unqualified free functions begin() and end() from
within a class with members begin() and end() without this hack. */
template< typename u >
auto b( u &c ) -> decltype( begin( c ) ) { return begin( c ); }
template< typename u >
auto e( u &c ) -> decltype( end( c ) ) { return end( c ); }
}
template< typename iter >
struct range_proxy {
range_proxy( iter &in_first, iter in_last )
: first( in_first ), last( in_last ) {}
template< typename T >
range_proxy( iter &out_first, T &in_container )
: first( out_first ),
last( unpolluted::e( in_container ) ) {
out_first = unpolluted::b( in_container );
}
range_iterator_reference_wrapper< iter > begin() const
{ return first; }
range_iterator_reference_wrapper< iter > end()
{ return last; }
iter &first;
iter last;
};
template< typename iter >
range_proxy< iter > visible_range( iter &in_first, iter in_last )
{ return range_proxy< iter >( in_first, in_last ); }
template< typename iter, typename container >
range_proxy< iter > visible_range( iter &first, container &in_container )
{ return range_proxy< iter >( first, in_container ); }
Usage:
#include <vector>
#include <iostream>
std::vector< int > values{ 1, 3, 9 };
int main() {
// Either provide one iterator to see it through the whole container...
std::vector< int >::iterator i;
for ( auto &value : visible_range( i, values ) )
std::cout << "# " << i - values.begin() << " = " << ++ value << '\n';
// ... or two iterators to see the first incremented up to the second.
auto j = values.begin(), end = values.end();
for ( auto &value : visible_range( j, end ) )
std::cout << "# " << j - values.begin() << " = " << ++ value << '\n';
}
for(auto i : ForIterator(some_list)) {
// i is the iterator, which was returned by some_list.begin()
// might be useful for whatever reason
}
The implementation was not that difficult:
template <typename T> struct Iterator {
T& list;
typedef decltype(list.begin()) I;
struct InnerIterator {
I i;
InnerIterator(I i) : i(i) {}
I operator * () { return i; }
I operator ++ () { return ++i; }
bool operator != (const InnerIterator& o) { return i != o.i; }
};
Iterator(T& list) : list(list) {}
InnerIterator begin() { return InnerIterator(list.begin()); }
InnerIterator end() { return InnerIterator(list.end()); }
};
template <typename T> Iterator<T> ForIterator(T& list) {
return Iterator<T>(list);
}
//z 2014-06-12 13:26:11 L.202'38029 BG57IV3@XCL T2508411853.K.F636940351 [T11,L175,R6,V152]
6. auto 部分的简单指导原则:
auto x : 使用拷贝
auto &x : 使用引用,指向原item,并且可能变更其值
const auto&x :指向原item,并且保证不改变其值
7. MAP 例子
Each element of the container is a map<K,, which is a
V>::value_typetypedef for std::pair<const. Consequently, you'd write this as
K, V>
for (auto& kv : myMap) {
std::cout << kv.first << " has value " << kv.second << std::endl;
}
如前所述,为效率考虑,使用reference,如果不改变其值(如这里),还应该加上 const 。
8. 来自 ms 的例子
Executes statement repeatedly and sequentially for each element in expression.
for ( for-range-declaration : expression )
statement
Remarks
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 STL sequence whose range is defined by a begin() and end(). The name that is declared in the for-range-declaration portion is local to the for statement and cannot be re-declared in expression or statement. Note that the auto keyword is preferred in the for-range-declaration portion of the statement.
This code shows how to use ranged for loops to iterate through an array and a vector:
// range-based-for.cpp
// compile by using: cl /EHsc /nologo /W4
#include <iostream>
#include <vector>
using namespace std; int main()
{
// Basic 10-element integer array.
int x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Range-based for loop to iterate through the array.
for( int y : x ) { // Access by value using a copy declared as a specific type.
// Not preferred.
cout << y << " ";
}
cout << endl; // The auto keyword causes type inference to be used. Preferred. for( auto y : x ) { // Copy of 'x', almost always undesirable
cout << y << " ";
}
cout << endl; for( auto &y : x ) { // Type inference by reference.
// Observes and/or modifies in-place. Preferred when modify is needed.
cout << y << " ";
}
cout << endl; for( const auto &y : x ) { // Type inference by reference.
// Observes in-place. Preferred when no modify is needed.
cout << y << " ";
}
cout << endl;
cout << "end of integer array test" << endl;
cout << endl; // Create a vector object that contains 10 elements.
vector<double> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i + 0.14159);
} // Range-based for loop to iterate through the vector, observing in-place.
for( const auto &j : v ) {
cout << j << " ";
}
cout << endl;
cout << "end of vector test" << endl;
}
Here is the output:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
end of integer array test
0.14159 1.14159 2.14159 3.14159 4.14159 5.14159 6.14159 7.14159 8.14159 9.14159
end of vector test
A range-based for loop terminates when one of these in statement is executed: a break, return, or goto to a labeled statement outside the range-based for loop. A continue statement in a range-based for loop terminates only the current iteration.
Keep in mind these facts about range-based for:
Automatically recognizes arrays.
Recognizes containers that have .begin() and .end().
Uses argument-dependent lookup begin() and end() for anything else.
c++11 : range-based for loop的更多相关文章
- c++11介绍
C++11标准是 ISO/IEC 14882:2011 - Information technology -- Programming languages -- C++ 的简称[1] . C++11 ...
- C++ 11标准
C++11,也称为C++0x.为目前C++编程语言的最新正式标准(ISO/IEC 14882:2011).它将取代第二版标准ISO/IEC 14882:2003(第一版ISO/IEC 14882:19 ...
- C++进阶引导
1.C++的用途和意义 t0185b047e29feffc26.jpg 总体来说,C++作为一门软件开发语言,它的流行度是在减少的.主要原因在于语言的复杂和灵活导致软件开发成本提高,这体现在开发周期和 ...
- C++ 如何进阶?
1.C++的用途和意义 总体来说,C++作为一门软件开发语言,它的流行度是在减少的.主要原因在于语言的复杂和灵活导致软件开发成本提高,这体现在开发周期和人力上.它不适用于startup公司的快速开发, ...
- Bash For Loop Examples for Your Linux Shell Scripting--ref
There are two types of bash for loops available. One using the “in” keyword with list of values, ano ...
- 在C++98基础上学习C++11新特性
自己一直用的是C++98规范来编程,对于C++11只闻其名却没用过其特性.近期因为工作的需要,需要掌握C++11的一些特性,所以查阅了一些C++11资料.因为自己有C++98的基础,所以从C++98过 ...
- 实验4 —— [bx]和loop的使用
实验 综合使用 loop.[bx],编写完整汇编程序,实现向内存 b800:07b8 开始的连续 16 个字单元重复填充字数据 0403H. 以下为示例程序: assume cs:code # 1 c ...
- boost range
1.Algorithms Boost.Range is library that, on the first sight, provides algorithms similar to those p ...
- 11.2.0.4 ORA-15025 ORA-27041 IBM AIX RISC System/6000 Error: 13: Permission denied
ASM device error ORA-27041 ORA-15025 ORA-15081 (Doc ID 1487475.1) 描述总结:数据库的alert中发现大量ORA-27041 ORA-1 ...
- Sphinx 2.2.11-release reference manual
1. Introduction 1.1. About 1.2. Sphinx features 1.3. Where to get Sphinx 1.4. License 1.5. Credits 1 ...
随机推荐
- (转)asp.net动态设置标题title 关键字keywords 描述descrtptions
方法一 if (!IsPostBack){//Page title网页标题Page.Title = “我的网站标题”;//须将网页head标签设成服务器控件模式,即<head runat=&qu ...
- 使用Uploadify 时,同时使用了jQuery.Validition 验证控件时,在IE11上出现JS缺少对象错误。
场景: 使用jQuery.1.8.2 使用 Uploadify 3.2上传控件 使用jQuery.Validition 1.9 验证 使用IE 11 时,当鼠标点击上传按钮时,会出现JS 缺少对象错误 ...
- Objective-C 类型判断
可以通过 isKindOfClass 判断对象的类型 @interface A : NSObject @end @implementation A @end //// @interface AA : ...
- JQ 遍历节点
.children() : 取得匹配元素的子元素集合 .next() :取得匹配元素后面紧邻的同辈元素 .prev() :取得匹配元素前面紧邻的同辈元素 .siblings() :取得匹配元素前.后的 ...
- cas+tomcat+shiro实现单点登录-1-tomcat添加https协议
目录 1.tomcat添加https安全协议 2.下载cas server端部署到tomcat上 3.CAS服务器深入配置(连接MYSQL) 4.Apache Shiro 集成Cas作为cas cli ...
- (原)torch使用caffe时,提示CUDNN_STATUS_EXECUTION_FAILED
转载请注明出处: http://www.cnblogs.com/darkknightzh/p/6230227.html 提前说明:此文不能真正解决该问题,具体原因我也不知道... 以前使用某台电脑A上 ...
- Google Guava的splitter用法
google的guava库是个很不错的工具库,这次来学习其spliiter的用法,它是一个专门用来 分隔字符串的工具类,其中有四种用法,分别来小结 1 基本用法: String str = " ...
- ecshop代码详解之init.php
在includes/init.php目录下 因为工作原因,需要对ecshop二次开发,顺便记录一下对ecshop源代码的一些分析: 首先是init.php文件,这个文件在ecshop每个页面都会 调用 ...
- 百度云观测优化建议解决方案:未设置max-age或expires
网页的缓存是由 HTTP 消息头中的 “Cache-control” 来控制的,常见的取值有 private.no-cache.max-age.must-revalidate 等,默认为private ...
- javascript闭包作用
闭包的简单概念:闭包就是能够读取其他函数内部变量的函数. 函数内部的函数闭包的两个最大的作用读取函数内部的变量变量的值始终保持在内存中function A(){ var n=999; nAdd=fun ...