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?
You can return the vector from a function:
std::vector<int> f();
const std::vector<int> myVector = f();
Alternatively, use boost::assign::list_of.
@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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With