Search code examples
c++stdvectorallocator

2D vector allocator trouble


#include <iostream>
#include <vector>

int main()
{
    std::vector<double> test1(1);

    test1[100] = 5.;

    std::vector< std::vector <double > > test2(1, std::vector<double>(1,0));

    test2[50][100] = 5.;
}

test1 : resizes and allocates memory nicely

test2 :"Segmentation fault (core dumped)". Why?

Note: Cannot use matrix, since row size are unequal.

Summary: at(int): checks bounds and throws exception if necessary - no resizing

operator[](int) :doesnot check bounds - no resizing

push_back() : resizes increases capacity() by double if current capacity is small

size() : number of elements in vector

capacity() : maximum elements to hold before a re allocation is necessary


Solution

  • You access element with index 100 of a vector of size 1. You should not access index out of a vector bounds. Truth is that it is pure luck that it works in the first case instead of strange that second does not work.

    A vector expands on call to resize() or push_back, but simply accessing an index does not expand the vector's size. Instead it causes an undefined behavior.

    To fix the code do(change the sizes used when constructing the vectors):

    #include <iostream>
    #include <vector>
    
    int main()
    {
        std::vector<double> test1(101);
    
        test1[100] = 5.;
    
        std::vector< std::vector <double > > test2(51, std::vector<double>(101,0));
    
        test2[50][100] = 5.;
    }