在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上的此问题

原文链接: https://www.cnblogs.com/2944014083-zhiyu/p/14877695.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/211363

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 上午12:45
下一篇 2023年2月13日 上午12:46

相关推荐