Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 885
Samuel Avatar asked Feb 20 '20 12:02

Samuel


3 Answers

You can return the vector from a function:

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

Alternatively, use boost::assign::list_of.

like image 107
VLL Avatar answered Nov 10 '22 15:11

VLL


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

like image 30
Elazar Avatar answered Nov 10 '22 13:11

Elazar


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());
like image 27
Ted Lyngmo Avatar answered Nov 10 '22 13:11

Ted Lyngmo