-1

I just want to know which one is best (vector or list) on performance basis?

To understand that just wrote a simple tester to calculate the time for vectors and lists...

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

the exact difference between this two and which one is best among these?

Test code:

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;
}
Benjamin Bannier
  • 55,163
  • 11
  • 60
  • 80
Uday
  • 43
  • 1
  • 4

2 Answers2

0

It depends on the usage.

std::vector is a better container than std::list for most use cases. The use cases where you would need std::list is, if:

  1. You have a need to insert items in the middle.
  2. You have a need to remove items from the middle.
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    Even the two cases you mention are not necessarily faster. I would say the main use-case is where you want to guarantee pointer validity against insertion/deletion of elements, and you don't care too much about fast traversal, and don't need random access. – juanchopanza Apr 10 '14 at 07:03
0

If your actual workloads look like your tests, then you should be using vector.

You should only really use list if you are inserting or removing a lot of elements in the middle of the container. See this question for a more extended discussion.

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329