使用硬编码元素初始化 std::vector 的最简单方法是什么?

发布于 2024-08-21 08:41:04 字数 279 浏览 3 评论 0原文

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

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

How do I create a std::vector 并同样优雅地初始化它?

我知道的最好的方法是:

std::vector<int> ints;

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

有更好的方法吗?

I can create an array and initialize it like this:

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

How do I create a std::vector and initialize it similarly elegant?

The best way I know is:

std::vector<int> ints;

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

Is there a better way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(29

征棹 2024-08-28 08:41:04

如果您的编译器支持 C++11,您可以简单地执行以下操作:

std::vector<int> v = {1, 2, 3, 4};

GCC 自版本 4.4 起提供此功能。不幸的是,VC++ 2010 在这方面似乎落后了。

或者, Boost.Assign 库使用非-macro magic 允许以下操作:

#include <boost/assign/list_of.hpp>
...
std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);

或者:

#include <boost/assign/std/vector.hpp>
using namespace boost::assign;
...
std::vector<int> v;
v += 1, 2, 3, 4;

但请记住,这有一些开销(基本上,list_of 在底层构造了一个 std::deque),因此为了性能-关键代码你最好按照雅科比所说的去做。

If your compiler supports C++11, you can simply do:

std::vector<int> v = {1, 2, 3, 4};

This is available in GCC as of version 4.4. Unfortunately, VC++ 2010 seems to be lagging behind in this respect.

Alternatively, the Boost.Assign library uses non-macro magic to allow the following:

#include <boost/assign/list_of.hpp>
...
std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);

Or:

#include <boost/assign/std/vector.hpp>
using namespace boost::assign;
...
std::vector<int> v;
v += 1, 2, 3, 4;

But keep in mind that this has some overhead (basically, list_of constructs a std::deque under the hood) so for performance-critical code you'd be better off doing as Yacoby says.

随心而道 2024-08-28 08:41:04

一种方法是使用数组来初始化向量

static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );

One method would be to use the array to initialize the vector

static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
昇り龍 2024-08-28 08:41:04

如果可以的话,请使用现代 C++[11,14,17,20,...] 方式:

std::vector<int> ints = {10, 20, 30};

循环遍历可变长度数组或使用 sizeof() 的旧方式在眼睛和精神上的开销完全没有必要。恶心。

If you can, use the modern C++[11,14,17,20,...] way:

std::vector<int> ints = {10, 20, 30};

The old way of looping over a variable-length array or using sizeof() is truly terrible on the eyes and completely unnecessary in terms of mental overhead. Yuck.

无可置疑 2024-08-28 08:41:04

在 C++0x 中,您将能够以与数组相同的方式执行此操作,但在当前标准中不行。

仅在语言支持的情况下,您可以使用:

int tmp[] = { 10, 20, 30 };
std::vector<int> v( tmp, tmp+3 ); // use some utility to avoid hardcoding the size here

如果您可以添加其他库,您可以尝试 boost::assignment:

vector<int> v = list_of(10)(20)(30);

为了避免对数组的大小进行硬编码:

// option 1, typesafe, not a compile time constant
template <typename T, std::size_t N>
inline std::size_t size_of_array( T (&)[N] ) {
   return N;
}
// option 2, not typesafe, compile time constant
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))

// option 3, typesafe, compile time constant
template <typename T, std::size_t N>
char (&sizeof_array( T(&)[N] ))[N];    // declared, undefined
#define ARRAY_SIZE(x) sizeof(sizeof_array(x))

In C++0x you will be able to do it in the same way that you did with an array, but not in the current standard.

With only language support you can use:

int tmp[] = { 10, 20, 30 };
std::vector<int> v( tmp, tmp+3 ); // use some utility to avoid hardcoding the size here

If you can add other libraries you could try boost::assignment:

vector<int> v = list_of(10)(20)(30);

To avoid hardcoding the size of an array:

// option 1, typesafe, not a compile time constant
template <typename T, std::size_t N>
inline std::size_t size_of_array( T (&)[N] ) {
   return N;
}
// option 2, not typesafe, compile time constant
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))

// option 3, typesafe, compile time constant
template <typename T, std::size_t N>
char (&sizeof_array( T(&)[N] ))[N];    // declared, undefined
#define ARRAY_SIZE(x) sizeof(sizeof_array(x))
献世佛 2024-08-28 08:41:04

在 C++11 中:

#include <vector>
using std::vector;
...
vector<int> vec1 { 10, 20, 30 };
// or
vector<int> vec2 = { 10, 20, 30 };

使用 Boost list_of

#include <vector>
#include <boost/assign/list_of.hpp>
using std::vector;
...
vector<int> vec = boost::assign::list_of(10)(20)(30);

使用 Boost 分配:

#include <vector>
#include <boost/assign/std/vector.hpp>
using std::vector;
...
vector<int> vec;
vec += 10, 20, 30;

传统 STL:

#include <vector>
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );

具有通用宏的传统 STL:

#include <vector>
#define ARRAY_SIZE(ar) (sizeof(ar) / sizeof(ar[0])
#define ARRAY_END(ar) (ar + ARRAY_SIZE(ar))
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, ARRAY_END(arr));

具有向量初始值设定项宏的传统 STL:

#include <vector>
#define INIT_FROM_ARRAY(ar) (ar, ar + sizeof(ar) / sizeof(ar[0])
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec INIT_FROM_ARRAY(arr);

In C++11:

#include <vector>
using std::vector;
...
vector<int> vec1 { 10, 20, 30 };
// or
vector<int> vec2 = { 10, 20, 30 };

Using Boost list_of:

#include <vector>
#include <boost/assign/list_of.hpp>
using std::vector;
...
vector<int> vec = boost::assign::list_of(10)(20)(30);

Using Boost assign:

#include <vector>
#include <boost/assign/std/vector.hpp>
using std::vector;
...
vector<int> vec;
vec += 10, 20, 30;

Conventional STL:

#include <vector>
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );

Conventional STL with generic macros:

#include <vector>
#define ARRAY_SIZE(ar) (sizeof(ar) / sizeof(ar[0])
#define ARRAY_END(ar) (ar + ARRAY_SIZE(ar))
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, ARRAY_END(arr));

Conventional STL with a vector initializer macro:

#include <vector>
#define INIT_FROM_ARRAY(ar) (ar, ar + sizeof(ar) / sizeof(ar[0])
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec INIT_FROM_ARRAY(arr);
得不到的就毁灭 2024-08-28 08:41:04

我倾向于

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);

I tend to declare

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

in a utility header somewhere and then all that's required is:

const double values[] = { 2.0, 1.0, 42.0, -7 };
std::vector<double> array = makeVector(values);
翻身的咸鱼 2024-08-28 08:41:04

在 C++11 之前

static const int arr[] = {10, 20, 30};
vector<int> v(arr, arr + sizeof(arr) / sizeof(arr[0]));

我们还可以这样做:

vector<int> v;
v.push_back(SomeValue);
// ...

自 C++11

使用 copy-list-初始化

vector<int> v = {1, 3, 5, 7};

我们可以使用 direct-list-initialization 来完成此操作好吧:

vector<int> v {1, 3, 5, 7}; // Notice .. no "=" sign

从 C++17 开始

类模板参数推导 (CTAD) 让您省略模板参数:

vector v = {1, 3, 5, 7};

Before C++11

static const int arr[] = {10, 20, 30};
vector<int> v(arr, arr + sizeof(arr) / sizeof(arr[0]));

We can also do:

vector<int> v;
v.push_back(SomeValue);
// ...

Since C++11

Using copy-list-initialization:

vector<int> v = {1, 3, 5, 7};

We can do this using direct-list-initialization well:

vector<int> v {1, 3, 5, 7}; // Notice .. no "=" sign

Since C++17

Class template argument deduction (CTAD) lets you omit the template arguments:

vector v = {1, 3, 5, 7};
深海夜未眠 2024-08-28 08:41:04

开始于:

int a[] = {10, 20, 30}; //I'm assuming 'a' is just a placeholder

如果您没有 C++11 编译器并且不想使用 Boost:

const int a[] = {10, 20, 30};
const std::vector<int> ints(a, a+sizeof(a)/sizeof(int)); //Make it const if you can

如果您没有 C++11 编译器并且可以使用 Boost:

#include <boost/assign.hpp>
const std::vector<int> ints = boost::assign::list_of(10)(20)(30);

如果您有 C++ 11 编译器:

const std::vector<int> ints = {10,20,30};

Starting with:

int a[] = {10, 20, 30}; //I'm assuming 'a' is just a placeholder

If you don't have a C++11 compiler and you don't want to use Boost:

const int a[] = {10, 20, 30};
const std::vector<int> ints(a, a+sizeof(a)/sizeof(int)); //Make it const if you can

If you don't have a C++11 compiler and can use Boost:

#include <boost/assign.hpp>
const std::vector<int> ints = boost::assign::list_of(10)(20)(30);

If you do have a C++11 compiler:

const std::vector<int> ints = {10,20,30};
行至春深 2024-08-28 08:41:04

对于向量初始化 -

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]);
}

除此之外,前面的答案中还使用一些代码描述了各种其他方法。在我看来,这些方式很容易记住,而且写起来也很快。

For vector initialisation -

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

can be done if you have a C++11 compiler.

Else, you can have an array of the data and then use a for loop.

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

Apart from these, there are various other ways described in previous answers using some code. In my opinion, these ways are easy to remember and quick to write.

薄荷港 2024-08-28 08:41:04

最简单的方法是:

vector<int> ints = {10, 20, 30};

The easiest way to do it is:

vector<int> ints = {10, 20, 30};
新一帅帅 2024-08-28 08:41:04

如果您的编译器支持 Variadic 宏(对于大多数现代编译器来说都是如此),那么您可以使用下面的宏将向量初始化变成单行:

#define INIT_VECTOR(type, name, ...) \
static const type name##_a[] = __VA_ARGS__; \
vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))

使用此宏,您可以使用如下代码定义一个初始化向量:

INIT_VECTOR(int, my_vector, {1, 2, 3, 4});

这将创建一个名为 my_vector 的新整数向量,其中包含元素 1、2、3、4。

If your compiler supports Variadic macros (which is true for most modern compilers), then you can use the following macro to turn vector initialization into a one-liner:

#define INIT_VECTOR(type, name, ...) \
static const type name##_a[] = __VA_ARGS__; \
vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))

With this macro, you can define an initialized vector with code like this:

INIT_VECTOR(int, my_vector, {1, 2, 3, 4});

This would create a new vector of ints named my_vector with the elements 1, 2, 3, 4.

锦爱 2024-08-28 08:41:04

我使用 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;
}

演示

I build my own solution using va_arg. This solution is C++98 compliant.

#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

嘿咻 2024-08-28 08:41:04

如果你不想使用 Boost,但想享受语法,比如

std::vector<int> v;
v+=1,2,3,4,5;

只包含这段代码

template <class T> class vector_inserter{
public:
    std::vector<T>& v;
    vector_inserter(std::vector<T>& v):v(v){}
    vector_inserter& operator,(const T& val){v.push_back(val);return *this;}
};
template <class T> vector_inserter<T> operator+=(std::vector<T>& v,const T& x){
    return vector_inserter<T>(v),x;
}

If you don't want to use Boost, but want to enjoy syntax like

std::vector<int> v;
v+=1,2,3,4,5;

just include this chunk of code

template <class T> class vector_inserter{
public:
    std::vector<T>& v;
    vector_inserter(std::vector<T>& v):v(v){}
    vector_inserter& operator,(const T& val){v.push_back(val);return *this;}
};
template <class T> vector_inserter<T> operator+=(std::vector<T>& v,const T& x){
    return vector_inserter<T>(v),x;
}
于我来说 2024-08-28 08:41:04

在 C++11 中:

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

In C++11:

static const int a[] = {10, 20, 30};
vector<int> vec (begin(a), end(a));
浪推晚风 2024-08-28 08:41:04

最近的重复问题有此答案,作者:维克托·塞尔。对我来说,它很紧凑,视觉上很有吸引力(看起来像是你在“塞入”值),不需要 C++11 或第三方模块,并避免使用额外的(写入的)变量。下面是我如何使用它并进行一些更改。我将来可能会转而扩展向量和/或 va_arg 的功能。


// Based on answer by "Viktor Sehr" on Stack Overflow
// https://stackoverflow.com/a/8907356
//
template <typename T>
class mkvec {
    public:
        typedef mkvec<T> my_type;
        my_type& operator<< (const T& val) {
            data_.push_back(val);
            return *this;
        }
        my_type& operator<< (const std::vector<T>& inVector) {
            this->data_.reserve(this->data_.size() + inVector.size());
            this->data_.insert(this->data_.end(), inVector.begin(), inVector.end());
            return *this;
        }
        operator std::vector<T>() const {
            return data_;
        }
    private:
        std::vector<T> data_;
};

std::vector<int32_t> vec1;
std::vector<int32_t> vec2;

vec1 = mkvec<int32_t>() << 5 << 8 << 19 << 79;
// vec1 = (5, 8, 19, 79)
vec2 = mkvec<int32_t>() << 1 << 2 << 3 << vec1 << 10 << 11 << 12;
// vec2 = (1, 2, 3, 5, 8, 19, 79, 10, 11, 12)

A more recent duplicate question has this answer by Viktor Sehr. For me, it is compact, visually appealing (looks like you are 'shoving' the values in), doesn't require C++11 or a third-party module, and avoids using an extra (written) variable. Below is how I am using it with a few changes. I may switch to extending the function of vector and/or va_arg in the future instead.


// Based on answer by "Viktor Sehr" on Stack Overflow
// https://stackoverflow.com/a/8907356
//
template <typename T>
class mkvec {
    public:
        typedef mkvec<T> my_type;
        my_type& operator<< (const T& val) {
            data_.push_back(val);
            return *this;
        }
        my_type& operator<< (const std::vector<T>& inVector) {
            this->data_.reserve(this->data_.size() + inVector.size());
            this->data_.insert(this->data_.end(), inVector.begin(), inVector.end());
            return *this;
        }
        operator std::vector<T>() const {
            return data_;
        }
    private:
        std::vector<T> data_;
};

std::vector<int32_t> vec1;
std::vector<int32_t> vec2;

vec1 = mkvec<int32_t>() << 5 << 8 << 19 << 79;
// vec1 = (5, 8, 19, 79)
vec2 = mkvec<int32_t>() << 1 << 2 << 3 << vec1 << 10 << 11 << 12;
// vec2 = (1, 2, 3, 5, 8, 19, 79, 10, 11, 12)
友谊不毕业 2024-08-28 08:41:04

您可以使用 boost::assign 来做到这一点:

vector<int> values;
values += 1,2,3,4,5,6,7,8,9;

详细信息在这里

You can do that using boost::assign:

vector<int> values;
values += 1,2,3,4,5,6,7,8,9;

Details are here.

玩物 2024-08-28 08:41:04

以下方法可用于在 C++ 中初始化向量。

  1. int arr[] = {1, 3, 5, 6};矢量v(arr, arr + sizeof(arr)/sizeof(arr[0]));

  2. 向量v; v.push_back(1); v.push_back(2); v.push_back(3); 等等

  3. vectorv = {1, 3, 5, 7};

第三个仅在 C++11 及以上版本。

The below methods can be used to initialize the vector in C++.

  1. int arr[] = {1, 3, 5, 6}; vector<int> v(arr, arr + sizeof(arr)/sizeof(arr[0]));

  2. vector<int>v; v.push_back(1); v.push_back(2); v.push_back(3); and so on

  3. vector<int>v = {1, 3, 5, 7};

The third one is allowed only in C++11 onwards.

夏の忆 2024-08-28 08:41:04

这里有很多很好的答案,但是由于我在阅读本文之前独立地得出了自己的答案,所以我想无论如何我都会把我的答案扔在这里......

这是我为此使用的一种方法,它将在编译器中通用和平台:

创建一个结构或类作为对象集合的容器。为 << 定义运算符重载函数。

class MyObject;

struct MyObjectList
{
    std::list<MyObject> objects;
    MyObjectList& operator<<( const MyObject o )
    { 
        objects.push_back( o );
        return *this; 
    }
};

您可以创建将结构体作为参数的函数,例如:

someFunc( MyObjectList &objects );

然后,您可以调用该函数,如下所示:

someFunc( MyObjectList() << MyObject(1) <<  MyObject(2) <<  MyObject(3) );

这样,您可以在一个干净的行中构建并将动态大小的对象集合传递给函数!

There are a lot of good answers here, but since I independently arrived at my own before reading this, I figured I'd toss mine up here anyway...

Here's a method that I'm using for this which will work universally across compilers and platforms:

Create a struct or class as a container for your collection of objects. Define an operator overload function for <<.

class MyObject;

struct MyObjectList
{
    std::list<MyObject> objects;
    MyObjectList& operator<<( const MyObject o )
    { 
        objects.push_back( o );
        return *this; 
    }
};

You can create functions which take your struct as a parameter, e.g.:

someFunc( MyObjectList &objects );

Then, you can call that function, like this:

someFunc( MyObjectList() << MyObject(1) <<  MyObject(2) <<  MyObject(3) );

That way, you can build and pass a dynamically sized collection of objects to a function in one single clean line!

空名 2024-08-28 08:41:04

如果您想要与 Boost::assign 具有相同一般顺​​序的东西,而不创建对 Boost 的依赖,那么以下内容至少有点相似:

template<class T>
class make_vector {
    std::vector<T> data;
public:
    make_vector(T const &val) { 
        data.push_back(val);
    }

    make_vector<T> &operator,(T const &t) {
        data.push_back(t);
        return *this;
    }

    operator std::vector<T>() { return data; }
};

template<class T> 
make_vector<T> makeVect(T const &t) { 
    return make_vector<T>(t);
}

虽然我希望使用它的语法更清晰,但它仍然不是特别糟糕:

std::vector<int> x = (makeVect(1), 2, 3, 4);

If you want something on the same general order as Boost::assign without creating a dependency on Boost, the following is at least vaguely similar:

template<class T>
class make_vector {
    std::vector<T> data;
public:
    make_vector(T const &val) { 
        data.push_back(val);
    }

    make_vector<T> &operator,(T const &t) {
        data.push_back(t);
        return *this;
    }

    operator std::vector<T>() { return data; }
};

template<class T> 
make_vector<T> makeVect(T const &t) { 
    return make_vector<T>(t);
}

While I wish the syntax for using it was cleaner, it's still not particularly awful:

std::vector<int> x = (makeVect(1), 2, 3, 4);
ぃ弥猫深巷。 2024-08-28 08:41:04
typedef std::vector<int> arr;

arr a {10, 20, 30};       // This would be how you initialize while defining

编译使用:

clang++ -std=c++11 -stdlib=libc++  <filename.cpp>
typedef std::vector<int> arr;

arr a {10, 20, 30};       // This would be how you initialize while defining

To compile use:

clang++ -std=c++11 -stdlib=libc++  <filename.cpp>
绮筵 2024-08-28 08:41:04
// Before C++11
// I used following methods:

// 1.
int A[] = {10, 20, 30};                              // original array A

unsigned sizeOfA = sizeof(A)/sizeof(A[0]);           // calculate the number of elements

                                                     // declare vector vArrayA,
std::vector<int> vArrayA(sizeOfA);                   // make room for all
                                                     // array A integers
                                                     // and initialize them to 0 

for(unsigned i=0; i<sizeOfA; i++)
    vArrayA[i] = A[i];                               // initialize vector vArrayA


//2.
int B[] = {40, 50, 60, 70};                          // original array B

std::vector<int> vArrayB;                            // declare vector vArrayB
for (unsigned i=0; i<sizeof(B)/sizeof(B[0]); i++)
    vArrayB.push_back(B[i]);                         // initialize vArrayB

//3.
int C[] = {1, 2, 3, 4};                              // original array C

std::vector<int> vArrayC;                            // create an empty vector vArrayC
vArrayC.resize(sizeof(C)/sizeof(C[0]));              // enlarging the number of 
                                                     // contained elements
for (unsigned i=0; i<sizeof(C)/sizeof(C[0]); i++)
     vArrayC.at(i) = C[i];                           // initialize vArrayC


// A Note:
// Above methods will work well for complex arrays
// with structures as its elements.
// Before C++11
// I used following methods:

// 1.
int A[] = {10, 20, 30};                              // original array A

unsigned sizeOfA = sizeof(A)/sizeof(A[0]);           // calculate the number of elements

                                                     // declare vector vArrayA,
std::vector<int> vArrayA(sizeOfA);                   // make room for all
                                                     // array A integers
                                                     // and initialize them to 0 

for(unsigned i=0; i<sizeOfA; i++)
    vArrayA[i] = A[i];                               // initialize vector vArrayA


//2.
int B[] = {40, 50, 60, 70};                          // original array B

std::vector<int> vArrayB;                            // declare vector vArrayB
for (unsigned i=0; i<sizeof(B)/sizeof(B[0]); i++)
    vArrayB.push_back(B[i]);                         // initialize vArrayB

//3.
int C[] = {1, 2, 3, 4};                              // original array C

std::vector<int> vArrayC;                            // create an empty vector vArrayC
vArrayC.resize(sizeof(C)/sizeof(C[0]));              // enlarging the number of 
                                                     // contained elements
for (unsigned i=0; i<sizeof(C)/sizeof(C[0]); i++)
     vArrayC.at(i) = C[i];                           // initialize vArrayC


// A Note:
// Above methods will work well for complex arrays
// with structures as its elements.
情绪少女 2024-08-28 08:41:04

在编写测试时,无需定义变量即可创建内联向量,非常方便,例如:

assert(MyFunction() == std::vector<int>{1, 3, 4}); // <- this.

It is pretty convenient to create a vector inline without defining variable when writing test, for example:

assert(MyFunction() == std::vector<int>{1, 3, 4}); // <- this.
中性美 2024-08-28 08:41:04

“如何创建 STL 向量并像上面那样初始化它?以最少的打字工作量实现此目的的最佳方法是什么?”

初始化 STL 向量的最简单方法在初始化内置数组时,向量使用的是 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 个元素。

"How do I create an STL vector and initialize it like the above? What is the best way to do so with the minimum typing effort?"

The easiest way to initialize a vector as you've initialized your built-in array is using an initializer list which was introduced in 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 is 3 elements in size after Assigning (labeled statement) is executed.

浮世清欢 2024-08-28 08:41:04

有多种方法可以对向量进行硬编码。我将分享几种方法:

  1. 通过逐一推送值来初始化

    // 创建一个空向量
    矢量向量;
    
    vect.push_back(10);
    vect.push_back(20);
    vect.push_back(30);
    
  2. 像数组一样初始化

    向量;向量{10,20,30};
    
  3. 从数组初始化

    int arr[] = { 10, 20, 30 };
    int n = sizeof(arr) / sizeof(arr[0]);
    
    矢量 vect(arr, arr + n);
    
  4. 从另一个向量初始化

    向量;向量1{10,20,30};
    
    矢量 vect2(vect1.begin(), vect1.end());
    

There are various ways to hardcode a vector. I will share few ways:

  1. Initializing by pushing values one by one

    // Create an empty vector
    vector<int> vect;
    
    vect.push_back(10);
    vect.push_back(20);
    vect.push_back(30);
    
  2. Initializing like arrays

    vector<int> vect{ 10, 20, 30 };
    
  3. Initializing from an array

    int arr[] = { 10, 20, 30 };
    int n = sizeof(arr) / sizeof(arr[0]);
    
    vector<int> vect(arr, arr + n);
    
  4. Initializing from another vector

    vector<int> vect1{ 10, 20, 30 };
    
    vector<int> vect2(vect1.begin(), vect1.end());
    
送你一个梦 2024-08-28 08:41:04

如果数组是:

int arr[] = {1, 2, 3};
int len = (sizeof(arr)/sizeof(arr[0])); // finding length of array
vector < int > v;
v.assign(arr, arr+len); // assigning elements from array to vector 

If the array is:

int arr[] = {1, 2, 3};
int len = (sizeof(arr)/sizeof(arr[0])); // finding length of array
vector < int > v;
v.assign(arr, arr+len); // assigning elements from array to vector 
素衣风尘叹 2024-08-28 08:41:04

相关的是,如果您想让向量完全准备好进入快速语句(例如立即传递给另一个函数),您可以使用以下内容:

#define VECTOR(first,...) \
   ([](){ \
   static const decltype(first) arr[] = { first,__VA_ARGS__ }; \
   std::vector<decltype(first)> ret(arr, arr + sizeof(arr) / sizeof(*arr)); \
   return ret;})()

示例函数

template<typename T>
void test(std::vector<T>& values)
{
    for(T value : values)
        std::cout<<value<<std::endl;
}

示例使用

test(VECTOR(1.2f,2,3,4,5,6));

,但要小心 decltype,确保第一个值清楚是什么你想要的。

Related, you can use the following if you want to have a vector completely ready to go in a quick statement (e.g. immediately passing to another function):

#define VECTOR(first,...) \
   ([](){ \
   static const decltype(first) arr[] = { first,__VA_ARGS__ }; \
   std::vector<decltype(first)> ret(arr, arr + sizeof(arr) / sizeof(*arr)); \
   return ret;})()

example function

template<typename T>
void test(std::vector<T>& values)
{
    for(T value : values)
        std::cout<<value<<std::endl;
}

example use

test(VECTOR(1.2f,2,3,4,5,6));

though be careful about the decltype, make sure the first value is clearly what you want.

无言温柔 2024-08-28 08:41:04

B. Stroustrup 在 Prog 的 C++11 版本第 464 页的 16.2.10 Selfreference 中描述了一种链接操作的好方法。郎.其中函数返回引用,此处修改为向量。通过这种方式,您可以像 v.pb(1).pb(2).pb(3); 一样进行链接,但对于如此小的收益来说可能需要做太多的工作。

#include <iostream>
#include <vector>

template<typename T>
class chain
{
private:
    std::vector<T> _v;
public:
    chain& pb(T a) {
        _v.push_back(a);
        return *this;
    };
    std::vector<T> get() { return _v; };
};

using namespace std;

int main(int argc, char const *argv[])
{
    chain<int> v{};

    v.pb(1).pb(2).pb(3);

    for (auto& i : v.get()) {
        cout << i << endl;
    }

    return 0;
}

1
2
3

B. Stroustrup describes a nice way to chain operations in 16.2.10 Selfreference on page 464 in the C++11 edition of the Prog. Lang. where a function returns a reference, here modified to a vector. This way you can chain like v.pb(1).pb(2).pb(3); but may be too much work for such small gains.

#include <iostream>
#include <vector>

template<typename T>
class chain
{
private:
    std::vector<T> _v;
public:
    chain& pb(T a) {
        _v.push_back(a);
        return *this;
    };
    std::vector<T> get() { return _v; };
};

using namespace std;

int main(int argc, char const *argv[])
{
    chain<int> v{};

    v.pb(1).pb(2).pb(3);

    for (auto& i : v.get()) {
        cout << i << endl;
    }

    return 0;
}

1
2
3

廻憶裏菂餘溫 2024-08-28 08:41:04

最简单、符合人体工程学的方法(使用 C++ 11 或更高版本):

auto my_ints = {1,2,3};

The simplest, ergonomic way (with C++ 11 or later):

auto my_ints = {1,2,3};
如果没结果 2024-08-28 08:41:04

如果您想在自己的班级中使用它:

#include <initializer_list>
Vector<Type>::Vector(std::initializer_list<Type> init_list) : _size(init_list.size()),
_capacity(_size),
_data(new Type[_size])
{
    int idx = 0;
    for (auto it = init_list.begin(); it != init_list.end(); ++it)
        _data[idx++] = *it;
}

In case you want to have it in your own class:

#include <initializer_list>
Vector<Type>::Vector(std::initializer_list<Type> init_list) : _size(init_list.size()),
_capacity(_size),
_data(new Type[_size])
{
    int idx = 0;
    for (auto it = init_list.begin(); it != init_list.end(); ++it)
        _data[idx++] = *it;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文