3

I just started using c++, so I am still new to vectors and data structures. I'm wondering how to I add a int value into a specific index location of 2d vector. For example, I have a multidimensional vector "chessboard" initialized like:

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

0 0 0 0 0

How do I use the insert() method to insert a integer value 1 into say the x,y index [4,3] so It looks like this:

0 0 0 0 0

0 0 0 0 0

0 0 0 1 0

0 0 0 0 0

This Is my code so far:

vector<vector<int>> board(boardsize, vector<int> (boardsize, 0));
int x = 4; // x position for value to be inserted
int y = 3; // y position for value to be inserted
wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • 1
    [`std::vector::insert`](https://en.cppreference.com/w/cpp/container/vector/insert) doesn't do what you think. It increases the length of the vector, which makes the board non-rectangular after the call. What you want is `board[x][y] = 1`. – kotatsuyaki Oct 23 '22 at 04:11
  • Welcome to StackOverflow. If an answer solves your problem you could click '✔' to mark it as an accepted answer. With enough rep you can _also_ upvote any helpful answer (see here: https://stackoverflow.com/help/someone-answers). – wohlstad Oct 28 '22 at 03:31

1 Answers1

4

In order to change a value of an element of a std::vector, you can use std::vector::operator[].
For example in your case of a vector containing vectors:

board[x][y] = 1;

Note that std::vector::insert does not modify an existing element, but rather adds a new element (or elements) to the vector. This is not what you want since you set the final desired size of the vector upon construction.

A side note: better to avoid using namespace std; - see here: Why is "using namespace std;" considered bad practice?.

wohlstad
  • 12,661
  • 10
  • 26
  • 39