【发布时间】:2015-05-29 16:43:37
【问题描述】:
在一个函数中,我需要将一些整数存储在一个向量中。该函数被多次调用。我知道它们小于 10,但是对于函数的每次调用,这个数字都是可变的。怎样选择才能有更好的表现?
在示例中我发现:
std::vector<int> list(10)
std::vector<int>::iterator it=list.begin();
unsigned int nume_of_elements_stored;
for ( ... iterate on some structures ... ){
if (... a specific condition ...){
*it= integer from structures ;
it++;
nume_of_elements_stored++;
}
}
慢于:
std::vector<int> list;
unsigned int num_of_elements_stored(0);
for ( ... iterate on some structures ... ){
if (... a specific condition ...){
list.push_back( integer from structures )
}
}
num_of_elements_stored=list.size();
【问题讨论】:
-
如果
reserve+emplace_back实现优于两者,我不会感到震惊。 -
@WhozCraig:鉴于他在向量中放入的内容是
ints,emplace_back与复制相比产生影响的可能性非常小。 -
通常您不会将元素的数量单独存储在
vector中。只需使用size()。 -
我不得不问 - 为什么您认为数组创建和销毁(使用这种数量级的数组)是性能瓶颈?也许如果你补充说这是每秒执行无数次或其他什么,它可能会成为一个更大的问题。
标签: c++ performance vector std