What is the easiest way to initialize STD:: vector with hard coded elements?

I can create an array and initialize it like this:

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

How to create an std::vector and initialize it with the same elegance?

The best way I know:

std::vector<int> ints;


Is there a better way?

#1 building

The easiest way is:

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

#2 building

"How do I create an STL Vector and initialize it as above? With the least amount of typing, what's the best way? "

The easiest way to initialize a vector when initializing a built-in array is to use the initialization list introduced in C ++ 11.

// Initializing a vector that holds 2 elements of type int.
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.

After executing the allocation (tag statement), the size of the ivec is three elements.

#3 building

Related, if you want a vector to be completely ready to enter a quick statement (for example, pass it to another function immediately), you can use the following code:

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

Example use


Be careful with decltype, but make sure that the first value is clearly what you want.

#4 building

In C ++ 11:

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

Use boost list of:

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

Use promotion assignment:

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

General STL with general macro:

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

General STL with vector initialization 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);

#5 building

typedef std::vector<int> arr;

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

Compile using:

clang++ -std=c++11 -stdlib=libc++  <filename.cpp>

Posted by Talon on Tue, 07 Jan 2020 08:56:23 -0800