Home > Back-end >  Strange behaviour of vector in cpp
Strange behaviour of vector in cpp

Time:04-06

I was writing the naive version of the polynomial multiplication algorithm. I tried the following code:


#include <iostream>
#include <vector>
using namespace std;

vector<int> multp(const vector<int>& A, const vector<int>& B) {
    vector<int> result = {0};
    for(int i = 0; i < A.size()   B.size(); i  ) {
        result[i] = 0;
    }

    for (int i = 0; i < A.size(); i  ) {
        for (int j = 0; j < B.size(); j  ) {
            result[i   j]  = A[i] * B[j];
        }
    }

    return result;
}

int main () {
    vector<int> A = {1, 1};
    vector<int> B = {1, 1, 1};
    vector<int> result = multp(A, B);
    for (int i = 0; i < 4; i  ) {
        cout << result[i] << " ";
    }
    return 0;
}

And it worked just fine, but then, I changed the initialization of the vector from vector<int> result = {0}; to only vector<int> result;. Here I got a seg fault! Why is that? What difference does the = {0} make?

Also, in main, after the line vector<int> result = multp(A, B);, when I tried to print the length of the vector (cout << result.size() << endl;) I got 1 even tho the vector had 4 elements in it. Why does this happen?

CodePudding user response:

vector<int> result = {0}; creates a vector with one element so you aren't allowed to access anything but result[0]. An alternative would be to create the vector with as many elements that you need, A.size() B.size() - 1.

Example:

#include <iostream>
#include <vector>

std::vector<int> multp(const std::vector<int>& A, const std::vector<int>& B) {
    std::vector<int> result(A.size()   B.size() - 1); // correct size

    /* this is not needed, they will be 0 by default
    for(int i = 0; i < A.size()   B.size(); i  ) {
        result[i] = 0;
    }
    */

    for(size_t i = 0; i < A.size(); i  ) {
        for(size_t j = 0; j < B.size(); j  ) {
            result[i   j]  = A[i] * B[j];
        }
    }

    return result;
}

int main() {
    std::vector<int> A = {1, 1};
    std::vector<int> B = {1, 1, 1};
    std::vector<int> result = multp(A, B);

    for(int resval : result) {        // a convenient range based for-loop
        std::cout << resval << ' ';
    }
    std::cout << '\n';
}

CodePudding user response:

You can't modify or access array elements that don't exist. When you create an empty vector, it has no elements you can modify or access.

vector<int> result = {0}; // creates vector with one entry
for(int i = 0; i < A.size()   B.size(); i  ) {
    result[i] = 0; // legal only when i==0
}
  • Related