Assign a value to a certain position in a vector of a vector (2D)

3889 views c++
-1

Ok, im starting c++ and i want to assign a value to a specific position in a vector of a vector. I have done it with an array of array (2D) but now would like to do it with vectors.

   int main() {
        int newLine = 10;
        int newColumm = 10;
        const string WALL = "\u2588";
        cout << endl;
        string grille[10][10];
        for (int j = 0; j < newColumm + 1; j++) {
            int i = 0;
            grille[i][j] = WALL;
        }
        for (int j = 0; j < newColumm + 1; j++) {
            int i = newLine + 1;
            grille[i][j] = WALL;
        }

I would like to do the same thing with vectors. I Have :

  int main() {
    int newLine = 10;
    int newColumm = 10;
    const string WALL = "\u2588";
    cout << endl;
//    string grille[10][10];
    vector<vector<string>> grille;


    for (int j = 0; j < newColumm + 1; j++) {
        int i = 0;
        grille.at(i).at(j) = WALL;
    }
    for (int j = 0; j < newColumm + 1; j++) {
        int i = newLine + 1;
        grille.at(i).at(j) = WALL;
    }

It's obviously not working for the moment. (Sorry for my bad language, english is my second language...)

answered question

The at() method accesses an existing element in the vector. vector<vector<string>> grille; creates a completely empty vector. There's nothing existing there. That's why at() throws an exception. Open your C++ book to the chapter that explains how vectors work and read it. It should explain how to resize the vector to some size. Here, you have to: 1) resize the major dimension of the vector to N elements. 2) Resize each one of those elements, each individual std::vector<std::string> to a vector of 10 strings. P.S. const string WALL = "\u2588"; is wrong.

const string WALL = "\u2588"; is ok, its a special caracter of std library...

1 Answer

3

Your vector has no size. You are getting a std::range_error exception when you access the vector out-of-bounds. Since you are not handling exceptions, your program crashes.

The naive fix for this is to simply pre-allocate your vector to the dimensions you expect:

vector<vector<string>> grille(10, std::vector<string>(10));

Note that your for-loops will naturally overshoot anyway and you'll still get an exception, since they are actually looping to 10 inclusive. Remember that if you have 10 elements, then the valid indices are 0 to 9 inclusive.

posted this

Have an answer?

JD

Please login first before posting an answer.