Home > Blockchain >  C Vector subscript out of range when assigning values
C Vector subscript out of range when assigning values

Time:05-09

I am making a simple algorithm that counts how many times each number is represented in a vector. However, on compile it gives me the following error in popup: Vector subscript out of range and it is referencing to:

File: C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include\vector

Line: 1463

Code:

//get if highest value is negative
if (mx < 0) {
//store number of invidiual values in array invert, mn value
    std::vector<int> vl(mn * -1);
    for (int x = 0; x < arr.size(); x  ) {
        vl[arr[x] * -1]  = 1;
    }

Here I am working with negative values so I am inverting them to positive. Mn is representing the lowest value in the vector, which is then inverted so it becomes the highest, according to is created another vector Vl which stores a number of each value, so its size is mn * -1.

Full function:

void topSort(std::vector<int> &arr) {

//stores highest value
int mx = arr[0];
//stores lowest value
int mn = arr[0];

//get highest value
for (int i = 1; i < arr.size(); i  ) {
    if (arr[i] > mx) {
        mx = arr[i];
    }
    if (arr[i] < mn) {
        mn = arr[i];
    }
}
//get if highest value is negative
if (mx < 0) {
    //store number of invidiual values in array invert mx value
    std::vector<int> vl(mn * -1);
    for (int x = 0; x < arr.size(); x  ) {
        vl[arr[x] * -1]  = 1;
    }
    for (auto z : vl) {
        std::cout << z << "\n";
    }
} else {
    //store number of invidiual values in array
    std::vector<int> vl(mx);
}
}

CodePudding user response:

On the input [-3, -2, -1], your program will:

  1. Set mx=-1.
  2. Set mn=-3.
  3. Create a vector vl of size 3, so with the positions vl[0], vl[1] and vl[2].
  4. Try to set vl[3] = 1, which throws the error you are seeing, as vl[3] does not exist.

You should have std::vector<int> vl(mn * -1 1); to avoid out-of-range exceptions.

  • Related