I wrote the following code to test the value of capacity of a vector when it was constructed from another. This was inspired by a question asked here.
#include <iostream>
#include<vector>
int main()
{
std::vector<int> a;
a.reserve(65536);
a[0]=10;
std::vector<int> b(a); //NOTE: b is constructed from a
std::cout<<a[0]<<" " <<b[0];
}
The Program compiled successfully, but when it was run it threw the following error
Error during execution:
Segmentation Fault(core dumped).
Then to check that the value was initialized to vector a, I changed the code as shown below:
#include <iostream>
#include<vector>
int main()
{
std::vector<int> a(65536);
a[0]=10;
std::vector<int> b(a); //NOTE: b is constructed from a
std::cout<<a[0];
}
This time the program ran successfully without errors and gave the output as:
Output:
10
I then tried to changed it to the following code :
#include <iostream>
#include<vector>
int main()
{
std::vector<int> a(65536);
a[0]=10;
std::vector<int> b(a); //NOTE: b is constructed from a
std::cout<<a[0]<<" " <<b[0];
}
and to my surprise the following output came as expected :
Output:
10 10
I could not understand why the program ran successfully when the vector was initialized with it's size in the constructor but not when it's capacity was given using reserve().
I also came to know that the reserving capacity for vector using reserve() does not initialize the size of the vector. The following code also confused me further.
#include <iostream>
#include<vector>
int main()
{
std::vector<int> a;
a.reserve(1);
for(int i=0;i<5;i++)
a[i]=i;
std::vector<int> b(a); //NOTE: b is constructed from a
for(int i=0;i<5;i++)
std::cout<<a[i]<<" ";
std::cout<<"\n"<<a.size()<<" "<<a.capacity();
}
When executed it displays the following weird output:
Output:
0 1 2 3 4
0 1
The vector stored the 5 values but the size of the vector remained 0.
I couldn't understand this behaviour of vector. How could it take in values with the size not changing.