What is the best replacement for std::array<...>
if I don't want to have to provide constexpr size? I figured it would be best to just use std::vector
and do reserve(...)
on it, but maybe I'm overlooking something?
如果需要在运行时确定大小, std::vector
应该是正确选择的容器。
Yes, use std::vector
.
So if your code is
std:array<int, 42> my_array;
Replace it by
std:vector<int> my_array(42);
Note: you probably don't want to use reserve
, because it leaves the vector
empty. If you are using std::array
, your code doesn't have the concept of empty array, so it's best represented by a std::vector
instance that is filled at construction, and never resized.
std::vector<>
is probably your answer. I just wouldn't assume reserve()
guarantees any speedup.
Bjarne Stroustrup:
People sometimes worry about the cost of std::vector growing incrementally. I used to worry about that and used reserve() to optimize the growth. After measuring my code and repeatedly having trouble finding the performance benefits of reserve() in real programs, I stopped using it except where it is needed to avoid iterator invalidation (a rare case in my code). Again: measure before you optimize.
http://www.stroustrup.com/bs_faq2.html [See bottom of "Why are the standard containers so slow?"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.