基于范围的for循环
C++11基于范围的for循环,语法格式:
- declaration 表示遍历声明,在遍历过程中当前被遍历到的元素会被存储到声明的变量中
- expression 是要遍历的对象,它可以是 表达式、容器、数组、初始化列表等
for (declaration : expression)
{// 循环体
}
使用基于范围的for循环遍历容器
#include <iostream>
#include <vector>
using namespace std;int main() {vector<int> t{1, 2, 3, 4, 5};for(auto value : t){cout << value << " ";}cout << endl;return 0;
}
一、在容器遍历时修改值
上面的例子中,只是将容器遍历的当前元素拷贝到了声明的变量value中,因此无法对容器中的元素进行写操作,如果需要在元素遍历的过程中修改元素的值,需要使用引用&。
#include <iostream>
#include <vector>
using namespace std;int main() {vector<int> t{1, 2, 3, 4, 5};cout << "遍历修改之前的元素"<< endl;for(auto value : t){cout << value << " ";}cout << endl;cout << "遍历修改之后的元素"<< endl;for(auto& value : t){cout << ++value <<" ";}cout << endl;for(auto value : t){cout << value << " ";}cout << endl;return 0;
}
二、效率较高的只读遍历
对容器的遍历过程中,如果只是只读数据,不允许修改元素的值,可以使用const 定义保存元素数据的变量,在定义时建议使用 const auto &,这样相对于const auto 效率更高些
#include <iostream>
#include <vector>
using namespace std;int main() {vector<int> t{1, 2, 3, 4, 5};cout << "遍历修改之前的元素"<< endl;for (const auto& value : t){cout << value << " ";}return 0;
}
三、使用细节
1.关系型容器 k-v
#include <iostream>
#include <map>
#include <string>
using namespace std;int main (void){map <int,string> mymap{{1,"apple"},{2,"banana"},{3,"orange"}};//基于范围的for循环for (auto &item : mymap){cout<<"id:" << item.first << ",name" << item.second << endl;}//普通的for循环方式for (auto it = mymap.begin(); it!= mymap.end(); ++it){cout<<"id:" << it->first << ",name" << it->second << endl;}//不能修改 first的值 item.first是一个常量 item.second可以修改for(auto &item : mymap){cout<<"id:" << item.first << ",name" << item.second + "666" << endl;}return 0;}
-
使用普通的for循环方式(基于迭代器)遍历关联性容器, auto自动推导出的是一个迭代器类型,需要使用迭代器的方式取出元素中的键值对(和指针的操作方法相同):
it->first
it->second -
使用基于范围的for循环遍历关联性容器,auto自动推导出的类型是容器中的value_type,相当于一个对组(std::pair)对象,提取键值对的方式如下:
it.first
it.second
2.元素只读
对于set容器来说,内部的元素都是只读的,这是由容器的特性决定的,因此在for循环中auto & 会被视为const auto &。
#include <iostream>
#include <set>
using namespace std;int main(void){set<int> s{1,2,3,4,5,6};for(auto &item : s){cout << item++ << " "; //error 不能给常量赋值}return 0;
}
3.访问次数(对要遍历集合的访问次数)
#include <iostream>
#include <vector>
using namespace std;
vector<int> v{1,2,3,4,5};
vector<int>& getRange()
{cout<< "get vector range ..."<<endl;return v;
}int main(){for (auto val:getRange()){cout<<val<<" ";}cout<<endl;return 0;}
只访问一次