简体   繁体   English

如何在旧 C++ 中初始化 const std 向量?

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

My C++ compiler identification is GNU 4.4.1我的 C++ 编译器标识是 GNU 4.4.1

I think since c++ 11 you can initialize a vector this way:我认为从 c++ 11 开始,您可以通过以下方式初始化向量:

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.不幸的是,我没有使用 c++ 11,所以 myVector 只能由构造函数初始化。 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?有没有办法让我的向量在 c++98 中定义时被初始化,如上面的例子,或者等价的东西?

You can return the vector from a function:您可以从函数返回向量:

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

Alternatively, use boost::assign::list_of .或者,使用boost::assign::list_of

@vll's answer is probably better, but you can also do: @vll 的答案可能更好,但您也可以这样做:

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM