how-to initialize 'const std::vector' like a c array

后端 未结 10 773
走了就别回头了
走了就别回头了 2020-11-27 02:59

Is there an elegant way to create and initialize a const std::vector like const T a[] = { ... } to a fixed (and small) number of val

10条回答
  •  抹茶落季
    2020-11-27 03:18

    Not sure if I understood you right. I understand your question like this: you want to initialize a vector to a large number of elements. What's wrong with using push_back() on the vector? :-)

    If you know the number of elements to be stored (or are sure that it will store less than the next power of 2) you can do this, if you have a vector of pointers of type X (works only with pointers):

    std::vector< X* > v;
    v.reserve(num_elems);
    X* p = v.begin();
    for (int count = 0; count < num_elems; count++)
       p[count] = some_source[count];
    

    Beware of adding more than the next power of 2 elements, even if using push_back(). Pointers to v.begin() will then be invalid.

提交回复
热议问题