我可以创建一个数组并像这样初始化它:

int a[] = {10, 20, 30};

我如何创建一个std::vector和初始化它同样优雅?

我知道的最好的方法是:

std::vector<int> ints;

ints.push_back(10);
ints.push_back(20);
ints.push_back(30);

有没有更好的办法?


当前回答

c++ 11:

static const int a[] = {10, 20, 30};
vector<int> vec (begin(a), end(a));

其他回答

我倾向于宣称

template< typename T, size_t N >
std::vector<T> makeVector( const T (&data)[N] )
{
    return std::vector<T>(data, data+N);
}

在一个实用程序头的某处,然后所需要的是:

const double values[] = { 2.0, 1.0, 42.0, -7 };
std::vector<double> array = makeVector(values);

我使用va_arg构建自己的解决方案。该解决方案是c++ 98兼容的。

#include <cstdarg>
#include <iostream>
#include <vector>

template <typename T>
std::vector<T> initVector (int len, ...)
{
  std::vector<T> v;
  va_list vl;
  va_start(vl, len);
  for (int i = 0; i < len; ++i)
    v.push_back(va_arg(vl, T));
  va_end(vl);
  return v;
}

int main ()
{
  std::vector<int> v = initVector<int> (7,702,422,631,834,892,104,772);
  for (std::vector<int>::const_iterator it = v.begin() ; it != v.end(); ++it)
    std::cout << *it << std::endl;
  return 0;
}

Demo

对于向量初始化-

vector<int> v = {10, 20, 30}

如果你有c++ 11编译器就可以做到。

否则,你可以有一个数据数组,然后使用for循环。

int array[] = {10,20,30}
for(unsigned int i=0; i<sizeof(array)/sizeof(array[0]); i++)
{
     v.push_back(array[i]);
}

除此之外,在前面的回答中还描述了使用一些代码的各种其他方法。在我看来,这些方法容易记忆和快速书写。

下面的方法可用于在c++中初始化vector。

Int arr[] = {1,3,5,6};v(arr, arr + sizeof(arr)/sizeof(arr[0])); 向量v < int >;v.push_back (1);v.push_back (2);v.push_back (3);等等 向量<int>v = {1,3,5,7};

第三种方法只允许在c++ 11以后使用。

“我如何创建一个STL向量并像上面那样初始化它?用最少的打字工作量做到这一点的最佳方法是什么?”

在初始化内置数组时,初始化vector最简单的方法是使用c++ 11中引入的初始化列表。

// Initializing a vector that holds 2 elements of type int.
Initializing:
std::vector<int> ivec = {10, 20};


// The push_back function is more of a form of assignment with the exception of course
//that it doesn't obliterate the value of the object it's being called on.
Assigning
ivec.push_back(30);

执行赋值(标签语句)后,ivec大小为3个元素。