Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::list resize giving unexpected results

Tags:

c++

I am just learning and have a likely dumb question.

I have 2 containers, one is a vector and one is a list. They are both filled with the ints 1,2,3,4. After they are initialized I resize the container to a size of seven, then print the contents of the container.

#include <iostream>     
#include <vector>     
#include <list>

int main () 
{
std::list<int> lst= {1,2,3,4};
std::vector<int> vec = {1,2,3,4};

lst.resize(7);
vec.resize(7);

for (auto p = lst.begin(); p!=lst.end(); ++p)
  std::cout<<"List: "<<*p<<std::endl;

for (auto p = vec.begin(); p!=vec.end(); ++p)
  std::cout<<"Vector: "<<*p<<std::endl;

return 0;
}

In the output I am getting:

List: 1
List: 2
List: 3
List: 4
List: 0
List: 1994995248
List: 0
Vector: 1
Vector: 2
Vector: 3
Vector: 4
Vector: 0
Vector: 0
Vector: 0

Do I have to explicitly tell the list that I am adding 0s to avoid this?

like image 947
r-s Avatar asked Jun 05 '13 23:06

r-s


1 Answers

As other users posted, lst.resize(7,0) will solve your problem. Using lst.resize(7) and leaving off the initialization value tells the compiler that it doesn't matter what the value is (presumably because you're going to set it later). This allows the operating system to leave whatever random value is sitting in the memory, rather than spending resources on changing it.

The Vector container, on the other hand, includes code that automatically initializes your items to zero.

like image 62
IanPudney Avatar answered Oct 13 '22 04:10

IanPudney