C++ – how-to initialize ‘const std::vector‘ like a c array


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.

Best Solution

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


#include <boost/assign/std/vector.hpp>
using namespace boost::assign; // bring 'operator+=()' into scope

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

for C++11:

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