我有一个关于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.
}
请告诉我哪种方法最好,或者是否有更好的方法来完成工作。
非常感谢您提前的帮助!