简体   繁体   中英

How to assign a value to an element in 2D vector in C++?

How I can assign a number to specific element of 2D vector without modifying other elements in tha row?

I am trying to assign a value to an element in a 2D vector but the value is assigned to whole row in the vector.

void prinVec2D(vector<vector<int> > & A) {
    for (int i = 0; i < A.size(); i++) {
        for (int j = 0; j < A[i].size(); j++) {
            cout << A[i][i] << " ";
        }
        cout << endl;
    }
}

vector<vector<int> > generateMatrix(int A) {
    vector<vector<int> > ans(A, vector<int> (A, 0));
    ans[1][1] = 1;
    return ans;
}

int main() {
    int A = 4;
    vector<vector<int> > abc(A, vector<int>(A, 0));
    abc = generateMatrix(A);
    prinVec2D(abc);
    return 0;
}

Expected:

0 0 0 0 \\n 0 1 0 0 \\n 0 0 0 0 \\n 0 0 0 0 \\n

Output:

0 0 0 0 \\n 1 1 1 1 \\n 0 0 0 0 \\n 0 0 0 0 \\n

Are you printing the array wrong?

like:

//pseudo code
for(int i = 0, i < maxI; i++)
{
   string temp = "";
   for(int j = 0, j < maxJ; j++)
   {
      temp += array[1][j]; //note [1][j]
   }
   temp += newLine;
   //print temp
}

This code can do the job

#include<conio.h>
#include<iostream>
using namespace std;

int main()
{
    const int A = 4;
    int ans[A][A] = {0};
    int i, j;
    cout << "Original Sequence\n\n";
    for (i = 0; i < A; i++){
        for (j = 0; j < A; j++){
            cout << ans[i][j] << " ";
        }
        cout << endl;
    }
    //Value allocation
    ans[1][1] = 1;
    cout << "\nModified Sequence\n\n";
    for (i = 0; i < A; i++){
        for (j = 0; j < A; j++){
            cout << ans[i][j] << " ";
        }
        cout << endl;
    }
    _getch();
    return 0;
}

Output

Original Sequence

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

Modified Sequence

0 0 0 0
0 1 0 0
0 0 0 0
0 0 0 0

In

void prinVec2D(vector<vector<int> > &A)
{
  for(int i = 0; i < A.size(); i++){
    for(int j = 0;j < A[i].size(); j++){
      cout << A[i][i] <<" "; } cout <<endl;
  }
} 

cout << A[i][i] must be replaced by cout << A[i][j]

The assignment works (of course) you just print wrongly your array

PS PonWer has a good idea imagining you print wrong your array

Rather than indexing (and getting it wrong), you can just reference the elements of each vector

void printVec2D(const std::vector<std::vector<int> > & outer)
{
  for(auto & inner : outer)
  {
    for(auto & value : inner)
    {
      std::cout << value << " "; 
    } 
    std::cout << std::endl;
  }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM