std :: list和std :: vector的性能测试

时间:2014-04-10 06:51:34

标签: c++ stl

我只想知道哪一个最适合(vectorlist) 依据?

要明白,只是写了一个简单的测试人员来计算时间 vector s和list s ...

Vector code :
    1. started the timer
    2. pushing 3000 elements in to to the vector
    3. using iterator to access all the elements from the container and
      printing it
    4. stoped the timer
    5. running the vector code, getting the output as 0ms.

List code:
    1. start the timer
    2. pushing 3000 elements into the list
    3. using iterator to access all the elements from the container and
      printing it
    4. stop the timer
    5. running the list code,getting the output as 10ms.

But few of my friends are saying that `list` is best.....Can someone tell me

这两者之间的确切差异,哪一个最好?

测试代码:

int main() {
  int i;
  vector<int> vec;
  vector<int>::iterator vIter;
  clock_t tstart = 0, tstop = 0;
  tstart = clock();
  for (i = 0; i < 3000; i++) vec.push_back(i);
  for (vIter = vec.begin(); vIter != vec.end(); vIter++) cout << *vIter << endl;
  tstop = clock();
  std::cout << mstimer(tstart, tstop) << " (ms)" << std::endl;
  return 0;
}

2 个答案:

答案 0 :(得分:0)

这取决于使用情况。

对于大多数用例,

std::vector是比std::list更好的容器。您需要std::list的用例是:

  1. 您需要在中间插入物品。
  2. 您需要从中间删除项目。

答案 1 :(得分:0)

如果您的实际工作负载看起来像您的测试,那么您应该使用vector

如果要在容器的 middle 中插入或删除大量元素,则应该只使用list。有关更广泛的讨论,请参阅此question