Samuel
Samuel

Reputation: 866

How to initialize a const std vector in old c++?

My C++ compiler identification is GNU 4.4.1

I think since c++ 11 you can initialize a vector this way:

const std::vector<int> myVector = {1, 2, 3};
const std::vector<int> myVector2{1, 2, 3};

Unfortunately, I am not using c++ 11 so myVector can just be initilized by constructor. I need to create a vector that will never be modified. It has to be shared by differents functions within a class so it may be static as well, or even a class member. Is there a way to make my vector be initiliazed when it gets defined in c++98, as the examples from above, or something equivalent?

Upvotes: 5

Views: 947

Answers (3)

Ted Lyngmo
Ted Lyngmo

Reputation: 117493

You've already gotten two good answers. This is just a combination of both:

namespace detail {
    template<typename T, size_t N>
    size_t size(const T (&)[N]) { return N; }

    std::vector<int> vecinit() {
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        return std::vector<int>(arr, arr+size(arr));
    }
}

//...

const std::vector<int> myVector(detail::vecinit());

Upvotes: 3

Elazar
Elazar

Reputation: 21635

@vll's answer is probably better, but you can also do:

int temp[] = {1, 2, 3};
const std::vector<int> myVector(temp, temp + sizeof(temp)/sizeof(temp[0]));

It does however create two copies instead of one, and it pollutes the namespace with the name of the array.

Upvotes: 3

VLL
VLL

Reputation: 10165

You can return the vector from a function:

std::vector<int> f();
const std::vector<int> myVector = f();

Alternatively, use boost::assign::list_of.

Upvotes: 7

Related Questions