705

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?

Prateek Gupta
  • 119
  • 2
  • 7
Agnel Kurian
  • 57,975
  • 43
  • 146
  • 217
  • 1
    if you are not going to change the size of ints after initialization, consider using tr1 array. – zr. Feb 10 '10 at 11:21
  • 1
    @zr, you have me curious... if I needed fixed size, could I not use plain old arrays themselves? Looking at tr1 array right now... – Agnel Kurian Feb 10 '10 at 11:53
  • 2
    `tr1::array` is useful because ordinary arrays don't provide the interface of STL containers – Manuel Feb 10 '10 at 12:21
  • Changed the title to make this explicitly a C++03 question. It seemed easier than going through and fixing all the answers to make sense with the new standard C++. – T.E.D. Feb 24 '14 at 16:12
  • This is called [list initialization](https://en.cppreference.com/w/cpp/language/list_initialization). – alandawkins Aug 11 '18 at 08:00
  • Not exactly what is asked, but if you need to initialize the vector with just one value, you can use `vector::assign()` as well. – Aaron S Oct 07 '18 at 02:30
  • Just to say that `std::vector` lies in heap (it has a `new`) so, there is no performance profit from hardcoded elements. But if `push_back` are many, then a reallocation can take place which IS performance cost. Of course syntactically it is better to use the initialization list. – Chameleon Jun 05 '22 at 21:52

29 Answers29

758

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.

bobobobo
  • 64,917
  • 62
  • 258
  • 363
Manuel
  • 12,749
  • 1
  • 27
  • 35
  • Since vectors are self-sizing, would it be ok to initialize it as empty too? Like in the constructor: `this->vect = {};` ? – Azurespot Mar 08 '18 at 02:03
  • 3
    @Azurespot You can just initialise it, and it will be empty: `std::vector vector;` – Luke Apr 05 '18 at 23:33
  • 2
    Just in case somebody may be curious about `std::vector v = {1, 2, 3, 4};`, vector's `initializer list constructor` will be called for this sort of initializing, its doc can be find in the [`C++ 11` section](http://www.cplusplus.com/reference/vector/vector/vector/). – simomo Mar 01 '19 at 15:48
582

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]) );
Yacoby
  • 54,544
  • 15
  • 116
  • 120
  • 7
    @Agnel It will work fine without `static` or `const`, however they both make it more explicit as to how it should be used and allow the compiler to make additional optimizations. – Yacoby Feb 10 '10 at 16:55
  • 78
    I didn't downvoate this, but I was tempted. Mainly because this saves you almost nothing over just using the initialized array in the first place. However, that's really C++'s fault, not yours. – T.E.D. May 03 '11 at 18:50
  • 2
    Can you explain why you're using those parameters when defining the vec vector. – DomX23 Jan 27 '12 at 05:23
  • 16
    sizeof(array) is one of the few exceptions that allows to get the total size of elements of the array and NOT the arr pointer dimension. So basically he's using vector(pointer_to_first_element, pointer_to_first_element + size_in_bytes_of_the_whole_array / size_of_one_element) that is: vector(pointer_to_first_element, pointer_after_final_element). The type is already given with the , so the vector knows how much is one element. Remember that iterators can be treated as pointers so you're basically using the vector(iterator begin, iterator end) constructor – Johnny Pauling Aug 17 '12 at 12:58
  • Not only is this method easy and standalone without any extra requirements, but it can also be made forwards-compatible with C++0x and their container initialization lists with the help of a macro, which eases syntax and portability a lot. +1. – Luis Machuca Oct 21 '12 at 03:25
  • It seems that if I use static const string attr[]={"abc", "def","ghi"} that I can't use sizeof to get the array length. It also doesn't seem to work for arrays of char *'s. Am I doing something wrong? – qwerty9967 Mar 27 '13 at 13:49
  • 1
    Actually ... the sizeof trick works just fine until I pass the array into a function. Then it seems to not work any more. Is there a way around that? – qwerty9967 Mar 27 '13 at 14:03
  • @qwerty9967 When you pass an array into a function by pointer, you should always pass the size of the array as well, unless the function infers the size of the array from the array contents (e.g. if the last element contains terminating value etc.). That's why C++ has std::vector, so passing it by reference will solve your problem. – Victor K Apr 26 '13 at 08:10
  • 11
    @T.E.D: Sometimes you need to modify the resulting vector. For example, you may need to always have some default parameters and sometimes add a few customized to them. – DarkWanderer Feb 18 '14 at 09:24
  • Doesn't this imply that two duplicate copies of the integers are now being stored in memory? Is there at least a way to destroy the `static const int arr[]` afterward to free up that memory? Even without the `static` keyword, a global variable would remain allocated for the entirety of the program. This could become an issue when dealing with many/large vectors of doubles, strings, etc. – MasterHD Jul 14 '16 at 05:52
  • A solution involving an auxiliary variable, `sizeof()` and multiple arithmetic operations including a division is anything but "the easiest way". -1. – einpoklum Mar 11 '17 at 21:12
  • This answer could be slightly improved by accounting for the introduction of `constexpr` to the language. – François Andrieux May 17 '21 at 13:40
139

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.

Adam Erickson
  • 6,027
  • 2
  • 46
  • 33
  • 3
    In fairness, this was originally a C++03 question, but I hope that people/companies adopt the new standards. C++ still needs a variable-length array (VLA) implementation in the standard library similar to what is available in Eigen and Boost. – Adam Erickson Sep 16 '18 at 20:55
  • Unfortunately, this approach is problematic in some cases e.g. http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1467. Yuck. – Lightness Races in Orbit Feb 27 '19 at 12:31
  • If "list-initialization of an aggregate from an object of the same type" is your thing, probably there are bigger problems in your codebase... I can think of no application where it would justify the debugging problems. – Adam Erickson Jun 20 '19 at 23:30
  • answer from 2018 and still uses `={}`? – Noone AtAll Aug 03 '20 at 15:01
  • Still no need of `=` – backslashN Sep 13 '20 at 13:34
  • 1
    The answer uses the `=` and `{}` symbols to simplify the translation for programmers coming from other languages. Omitting the assignment operator when you are in fact assigning values is just weird. The compiler will remove the `=` operator anyway. – Adam Erickson Nov 18 '21 at 16:02
81

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))
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • Of course I didn't downvote but I have a question anyway: when is the size of an array not a compile time constant? I.e., in which cases would you use the first solution in your second snippet as opposed to the third one? – Manuel Feb 10 '10 at 11:26
  • +vote from my side. In C++0x you could make a `constexpr` of option 1. But then again, this won't be used anymore then :S – Sebastian Mach Feb 10 '10 at 11:36
  • 4
    @Manuel, the size of the array is part of the type, and as such it is a compile time constant. Now, option 1 uses that compile time constant 'N' as return value for a function. The return of a function is not a compile time, but runtime value, even if it will probably get inlined as the constant value at the place of call. The difference is that you cannot do: `int another[size_of_array(array)]`, while you can do `int another[ARRAY_SIZE(array)]`. – David Rodríguez - dribeas Feb 10 '10 at 11:45
  • @Manuel: incomplete array types also exist, like `int[]`. I can put a declaration of such an array in a header and define it somewhere else (with completed type). Then, the size is not known during compilation of all other traslation units that just include the header. Array-to-pointer decay still works, sizeof does not. – sellibitze Feb 10 '10 at 12:48
  • 2
    In option 3: I don't really get what you mean with "declared, undefined "? So the variable will not take additional memory? – To1ne Jun 06 '11 at 06:40
  • 2
    @To1ne that is actually a function declaration, not a variable. The reason for or defining it is that we don't actually want the function for anything else other than the `sizeof` expression that does not need a definition. While you can actually provide a definition, to do it right would require the static allocation of an array and returning a reference to it, and the next question would be what would make sense as values for the array? (Also note that this means one array per type/size combination of the function's instantiations!) Since the is no sensible use for it, I'd rather avoid it. – David Rodríguez - dribeas Jan 20 '12 at 12:51
  • The option 1 doesn't work in the case of empty array: `int arr[0] = {};` `std::size_t num = size_of_array(arr);` Compiler will print something like: `no matching function for call to 'size_of_array(int [0])' std::size_t num = size_of_array(arr);` – mhd Oct 11 '16 at 13:33
  • 2
    @mhd: You cannot construct an empty array in the language. 'int arr[0] = {};' is not valid C++ code. But you are right that if you want to initialize an empty vector and a non-empty vector you will have to use different constructs. Since C++11 this is a non-issue as you can use the initializer list constructor – David Rodríguez - dribeas Oct 13 '16 at 11:03
  • Your ARRAY_SIZE macro `#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))` is more unsafe than necessary. Please parenthesize it properly: `#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))` or `#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))` – Don Hatch Apr 17 '19 at 18:37
79

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mbells
  • 3,668
  • 3
  • 22
  • 21
  • 5
    C++11 also support `std::begin` and `std::end` for array, so a vector can also be initialized like `static const int arr[] = {10,20,30}; vector vec(begin(arr), end(arr));`. – Jaege Dec 17 '16 at 04:57
58

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
M. Tibbits
  • 8,400
  • 8
  • 44
  • 59
44

Before C++ 11:

Method 1

vector<int> v(arr, arr + sizeof(arr)/sizeof(arr[0]));

Method 2

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

C++ 11 onward below is also possible

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

We can do this as well

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

For C++ 17 onwards we can omit the type

vector v = {1, 3, 5, 7};
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
A J
  • 720
  • 1
  • 8
  • 11
  • Doesn't work for a vector with a single element. – ar2015 Aug 01 '21 at 11:09
  • 1
    *"For C++ 17 onwards we can omit the type"* -- Thanks to [Class template argument deduction (CTAD)](https://en.cppreference.com/w/cpp/language/class_template_argument_deduction) – Milan Apr 20 '22 at 18:20
29

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};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Carl
  • 43,122
  • 10
  • 80
  • 104
23

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tush_08
  • 339
  • 2
  • 7
22

The easiest way to do it is:

vector<int> ints = {10, 20, 30};
Paul Baltescu
  • 2,095
  • 4
  • 25
  • 30
16

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

L. F.
  • 19,445
  • 8
  • 48
  • 82
aloisdg
  • 22,270
  • 6
  • 85
  • 105
16

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.

Matt Ball
  • 1,434
  • 2
  • 17
  • 24
13

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Piti Ongmongkolkul
  • 2,110
  • 21
  • 20
  • 1
    I haven't been able to figure out how to use this code, but it looks interesting. – Daniel Buckmaster Apr 03 '12 at 10:06
  • It's like one of the comment above said. Just overloading += and comma operator. Putting parenthesis for clarity : `((((v+=1),2),3),4),5)` This is how it works: First, `vector += T` returns a vector_inserter lets call it `vi` which encapsulate the original vector then `vi,T` add T to original vector which `vi` encapsulate and return it self so that we can do `vi,T` again. – Piti Ongmongkolkul Apr 04 '12 at 01:10
  • this code didn't worked correctly on gcc 4.2.1 i think because of returning reference to a local variable inside += operator but idea is exellent. i edited code and there appears one more copy constructor. flow is now -> += -> ctor -> comma -> copy -> dtor -> comma ...... -> comma -> dtor. – Yevhen Jun 13 '12 at 12:56
  • I'd have probably overloaded << instead of +=. At least << already has vague side effect rules because of bit shifts and cout – Speed8ump Feb 23 '18 at 18:22
11

In C++11:

static const int a[] = {10, 20, 30};
vector<int> vec (begin(a), end(a));
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
BufBills
  • 8,005
  • 12
  • 48
  • 90
  • 21
    If you're using C++11 already, you may as well go for the direct approach - `vector arr = {10, 20, 30};`. – Bernhard Barker Feb 24 '15 at 13:09
  • Actually I had an incoming int[] (some C lib) and wanted to push into a vector (C++ lib). This answer helped, the rest didn't ;-) – Nebula Jul 20 '15 at 07:52
10

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)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Othermusketeer
  • 126
  • 1
  • 5
8

You can do that using boost::assign:

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

Details are here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
f4.
  • 3,814
  • 1
  • 23
  • 30
  • 21
    I haven't seen a worse case of operator overloading abuse in a long time. Does the `+=` there tack on 1,2,3,4.. to the end of values, or does it _add_ 1 to the 1st element, 2 to the 2nd element, 3 to the 3rd element (as syntax like this should in MATLAB-like languages) – bobobobo Nov 09 '13 at 20:42
7

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jay
  • 207
  • 2
  • 12
5

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!

Waqar
  • 8,558
  • 4
  • 35
  • 43
BuvinJ
  • 10,221
  • 5
  • 83
  • 96
4

"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.

Waqar
  • 8,558
  • 4
  • 35
  • 43
  • In the similar lines , I am trying to initialise the map, std::map catinfo = { {1, false} }; But then get this error error: in C++98 'catinfo' must be initialized by constructor, not by '{...}' – pdk Sep 08 '13 at 07:42
4
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>
Sam
  • 7,252
  • 16
  • 46
  • 65
shaveenk
  • 1,983
  • 7
  • 25
  • 37
  • Question states C++ 03 (not 11) – Mike P Sep 08 '14 at 09:55
  • 1
    I think it didn't specify 03 when I answered this. Don't remember perfectly though. However, it is still a useful answer for someone looking for a quick solution. – shaveenk Sep 08 '14 at 17:26
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);
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
4
// 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.
sg7
  • 6,108
  • 2
  • 32
  • 40
4

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 
Farid Chowdhury
  • 2,766
  • 1
  • 26
  • 21
  • Does this code compile? That last line looks like it would be a syntax error, since it would be parsed as `(std::v).assign(arr, arr + len);`, and there's no `v` in `namespace std`. Or did you mean `std::vector v; v.assign(...);`? – templatetypedef Jul 13 '21 at 21:21
  • Note that for you can use: `len = std::size(arr);`. It does the same thing under the hood. – Alexis Wilke Jun 24 '22 at 17:21
4

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.
Daniel
  • 980
  • 9
  • 20
4

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());
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anil Gupta
  • 147
  • 7
3

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.

Josh
  • 173
  • 3
  • 7
2

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

kometen
  • 6,536
  • 6
  • 41
  • 51
  • The armadillo library does this for matrix initialisation but uses the << operator instead of a named function: http://arma.sourceforge.net/docs.html#element_initialisation – Agnel Kurian Feb 19 '16 at 04:31
1

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

auto my_ints = {1,2,3};
nz_21
  • 6,140
  • 7
  • 34
  • 80
0

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;
}
NixoN
  • 661
  • 1
  • 6
  • 19