【问题标题】:quick vector initialization c++ [duplicate]快速向量初始化c ++ [重复]
【发布时间】:2011-01-17 21:06:05
【问题描述】:

可能的重复:
C++: Easiest way to initialize an STL vector with hardcoded elements
Using STL Allocator with STL Vectors

出于好奇,我想知道初始化向量的快速方法

我只知道这个

double inputar[]={1,0,0,0};
vector<double> input(inputar,inputar+4);

【问题讨论】:

标签: c++ syntax initialization vector


【解决方案1】:

恕我直言,这是当前 C++ 标准的缺陷之一。 Vector 可以很好地替代 C 数组,但初始化一个更像是 PITA。

我听说过的最好的是the Boost assignment package。根据文档,您可以这样做:

#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <boost/assert.hpp>; 
using namespace std;
using namespace boost::assign; // bring 'operator+=()' into scope

{
    vector<int> values;  
    values += 1,2,3,4,5,6,7,8,9; // insert values at the end of the container
    BOOST_ASSERT( values.size() == 9 );
    BOOST_ASSERT( values[0] == 1 );
    BOOST_ASSERT( values[8] == 9 );
}

【讨论】:

    猜你喜欢
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多