Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how-to initialize 'const std::vector<T>' like a c array

Tags:

c++

stl

Is there an elegant way to create and initialize a const std::vector<const T> like const T a[] = { ... } to a fixed (and small) number of values?
I need to call a function frequently which expects a vector<T>, but these values will never change in my case.

In principle I thought of something like

namespace {   const std::vector<const T> v(??); } 

since v won't be used outside of this compilation unit.

like image 676
vscharf Avatar asked Oct 23 '08 20:10

vscharf


People also ask

What is the correct way to initialize vector in C++?

Begin Declare v of vector type. Call push_back() function to insert values into vector v. Print “Vector elements:”. for (int a : v) print all the elements of variable a.

Are vectors initialized to zero C++?

A vector, once declared, has all its values initialized to zero.


1 Answers

For C++11:

vector<int> luggage_combo = { 1, 2, 3, 4, 5 }; 

Original answer:

You would either have to wait for C++0x or use something like Boost.Assign to do that.

e.g.:

#include <boost/assign/std/vector.hpp> using namespace boost::assign; // bring 'operator+=()' into scope  vector<int> v; v += 1,2,3,4,5; 
like image 182
Ferruccio Avatar answered Sep 23 '22 19:09

Ferruccio