加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 是否可以在一行中初始化具有增加值的向量?

发布时间:2020-12-16 10:41:26 所属栏目:百科 来源:网络整理
导读:是否可以借助初始化程序列表或其他C功能将两个初始化行合并为单个语句?向量值始终以1递增,但大小n不固定. #include numeric#include vector#include iostreamint main(){ int n = 10; // Can the two lines below be combined into a single statement? std
是否可以借助初始化程序列表或其他C功能将两个初始化行合并为单个语句?向量值始终以1递增,但大小n不固定.

#include <numeric>
#include <vector>
#include <iostream>

int main()
{
    int n = 10;

    // Can the two lines below be combined into a single statement?
    std::vector<int> v(n);
    std::iota(v.begin(),v.end(),1);

    for (int i : v)
        std::cout << i << std::endl;

    return 0;
}

解决方法

您可以使用 Boost.counting_iterator:

std::vector<int> v(boost::counting_iterator<int>(1),boost::counting_iterator<int>(n + 1));

(Live)现在,这是否值得,比你已经拥有的更容易阅读是由你来决定的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读