开发者

Why are there no capacity argument in the constructors for the containers?

If I want to set the capacity to a std::vector I have to call .reserve开发者_开发知识库(...), are there any reason why there is not a capacity argument in the constructor for the containers in stl, std::string, std::vector?


There is one obvious reason: what would such a constructor look like?

All of the sequence containers already have a constructor that can be called with a single integer argument. That constructor resizes the container to have the specified number of elements.

Yes, you could add a second parameter (like bool reserve_instead_of_resize) to be able to use this constructor for both initial resizes and initial reserves, but then I think the end result would be confusing.


You could simply make a function for creating a reserved vector:

// make_reserved_vector
template <typename... T>
std::vector<T...> make_reserved_vector(size_t n) {
    std::vector<T...> vec;
    vec.reserve(n);
    return vec;
}

and use as:

auto myvec = make_reserved_vector<int>(32768);


To create a vector, and specifying its capacity in the same time, create a vector with the wanted capacity, copy into it elements you want, and erase from the iterator returned by copy. If the constructor is slow, just write another constructor with special parameters that just reserves memory.

int main (int argc, char** argv) {
  std::vector<size_t> v (10, 0);
  size_t tmp [3] = {0, 1, 2};
  std::vector<size_t>::iterator i (v.begin ());
  i = std::copy ((const size_t*)tmp, (const size_t*) &tmp [3], v.begin ());
  v.erase (i, v.end ());
  std::cout << "\tv capacity == " << v.capacity () << std::endl;
}

will output :

v capacity == 10

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜