Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'std::out_of_range' what(): vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)

Tags:

c++

vector

c++14

I'm having a really hard time figuring out how to fix this error. I've looked everywhere and can't seem to find a solution.

My program is a key/value pair algorithm that uses a vector of vectors. It takes in a key and value then adds the value to the vector at position 'key' in the vector of vectors. I used vPos and vNeg as my vectors of vectors and used each depending on if key is positive or negative.

size simply returns the size of the sequence at position 'key' in the vector of vectors.

data returns a pointer to the first element in the sequence specified at position 'key'.

insert adds a new value to the sequence at position 'key'.

I think my private variables might not be initialized right, but I've tried everything I can come up with so any help is appreciated.

#include <algorithm>
#include <list>
#include <vector>
using namespace std;

class key_value_sequences {
public:
    int size(int key) const{
        if (key < 0){
            return vNeg.at(-key).size();
        }
        return vPos.at(key).size();
    }

    const int* data(int key) const{
    if (key < 0){
        if (vNeg.at(-key).size()==0) return nullptr;
        return vNeg.at(-key).data();
    }
    if (vPos.at(key).size() == 0) return nullptr;
    return vPos.at(key).data();
    }

    void insert(int key, int value){
        if (key < 0){
            vNeg.at(-key).push_back(value);
        }
        else{
        vPos.at(key).push_back(value);
        }
    }

private:
    vector<vector<int>> vPos;
    vector<vector<int>> vNeg;

}; // class key_value_sequences

#endif // A3_HPP
like image 556
Evan Avatar asked Dec 06 '25 05:12

Evan


1 Answers

You call vPos.at(N) but you never put anything in vPos. The error message is correct: you are indexing beyond the end of the vector.

You could do something like this:

if (key >= vPos.size()) vPos.resize(key + 1);
vPos.at(key).push_back(value);

Then you know key is a valid index in vPos.

like image 200
John Zwinck Avatar answered Dec 08 '25 17:12

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!