简体   繁体   English

如何在 C++ 中为二维向量中的元素赋值?

[英]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?如何在不修改该行中的其他元素的情况下为 2D 矢量的特定元素分配一个数字?

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.我正在尝试为 2D 向量中的元素分配一个值,但该值已分配给向量中的整行。

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 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 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] cout << A[i][i]必须替换为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 PS PonWer 有一个好主意,想象您打印错误的阵列

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;
  }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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