在C++中,初始化 vector 为1-n

        之前的文章 c++里面 vector的初始化方法介绍了常见的几种初始化,比如初始化大小,初始化大小的同时全部赋初值0(默认),1,2,3等等,或者直接把所有的元素都给初值一一匹配

背景

        都有了一一匹配的了,为什么还要写这篇文章呢?因为有时候 n可能会比较大,你全部写太多了,麻烦吧

核心代码

iota(v.begin(), v.end(), 初始值);

例如

iota(v.begin(), v.end(), 0); //[0 ,n-1]
iota(v.begin(), v.end(), -5); //[-5,n-6]

测试代码

#include <algorithm>     //这是 random_shuffle 的头文件
#include <iostream>
#include <numeric>     //这是 iota 的头文件
#include <vector>

using namespace std;

int main() {
    vector<int> v(10);
    iota(v.begin(), v.end(), -1);
    for (auto i : v) {
        cout << i << ' ';
    }
    cout << '\n';

    random_shuffle(v.begin(), v.end());
    cout << "Contents of the list, shuffled: ";
    for (auto i : v) {
        cout << i << ' ';
    }
    cout << '\n';
}

结果

-1 0 1 2 3 4 5 6 7 8
Contents of the list, shuffled: 7 0 8 1 -1 4 6 2 3 5

更多方法请参考StackOverflow上的此问题

posted on 2021-06-12 09:57  雾恋过往  阅读(857)  评论(0编辑  收藏  举报

Live2D