std::array,std::vector,基于范围的for循环

std::array除了有传统数组支持随机访问、效率高、存储大小固定等特点外,还支持迭代器访问、获取容量、获得原始指针等高级功能。而且它还不会退化成指针T *给开发人员造成困惑。

for( 元素名变量 : 广义集合) { 循环体 }

a.“元素名变量”可以是引用类型,以便直接修改集合元素的值;

b. “元素名变量”也可以是const类型,避免循环体修改元素的值

c. 其中“广义集合”就是“Range(范围)”,是一些元素组成的一个整体

基于范围的循环仅限于for语句,do…while(); 和while(){} 不支持基于范围的循环。

#include<iostream>
#include<array> //引入
#include<vector> //引入
using namespace std;

int main(){
    int a[]{1, 2, 3, 4};//旧的定义方式
    array<int, 4> a2 ={ 1, 2, 3, 4};
    vector<int> v  ={ 1, 2, 3 };
    vector<string> s = { "hello", "world", "!" };
    for (auto i:a2)
    {
        cout << i << endl;
    }
    for (auto &i:a2)//引用,改变每个元素,2倍
    {
        i = i * 2;
    }
    for (auto i : a2)
    {
        cout << i << endl;
    }

    return 0;
}

【参考】

https://blog.csdn.net/thinkerleo1997/article/details/80415059 C++11:尽量使用std::array来代替数组

https://blog.csdn.net/SENLINZM/article/details/38682233 C++11 array使用详解

猜你喜欢

转载自www.cnblogs.com/xixixing/p/12036254.html
std