我对 std::vector 有疑问。
我有一个非常占用内存的算法,我预见到预测向量大小并提前为向量保留足够的内存将对减少内存使用有很大帮助。
以下哪个更好:
for ( ... ) {
std::vector<Type> my_vector;
my_vector.reserve(stuff_count);
// Do stuff , and append stuff to my_vector.
}
或这个:
std::vector my_vector;
for ( ... ) {
my_vector.clear();
my_vector.reserve(stuff_count);
// Do stuff , and append stuff to my_vector.
}
请告诉我哪个最好,或者是否有更好的做事方式。
非常感谢您!