Frage

#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

War es hilfreich?

Lösung

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.;
}

Andere Tipps

test1 : resizes and allocates memory nicely

std::vector will resizes and allocates memory when call std::vector::push_back, but not random through random access operator

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

Below code accesses out of boundary of test1, test2:

test1[100] = 5.0;
test2[50][100] = 5.0;

You could test vector size to before access

if (test1.size() > 100))
{
    test1[100] = 5.0;
}  

Or could use std::vector::at function with try/catch block:

try
{
    test2.at(50).at(100) = 5.0;
}
catch(const std::exception& e)
{
   std::cout << e.what() << std::endl;
}    

You are accessing outside of the boinds of each vector:

std::vector<double> test1(1); // size 1 vector
test1[100] = 5.; // out of bounds access

The result is undefined behaviour. If you want to make a size 100 vector, do this:

std::vector<double> test1(101); // size 101 vector
test1[100] = 5.; // OK, access 101th element
test.push_back(42); // push element, size is now 102

If you want operator[] to automatically expand/insert, use a std::map:

#include <iostream>
#include <map>

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

    test1[100] = 5.; // Will insert one element into test1

    std::map< std::map <double > > test2;

    test2[50][100] = 5.; // will create a new map<double> and insert one element into it.
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top