替换2D矢量C++中的数据

Replace data in 2D vector C++

本文关键字:数据 C++ 2D 矢量 替换      更新时间:2023-10-16

我正试图在2D向量中搜索一个字符,即"?"并将其替换为"x"。

我用一个向量做这项任务并没有问题,但2D向量实现一直有问题,请参阅下面的代码。

#include <iostream>
#include <vector>
using namespace std;

int main()
{
        // An empty vector of vectors
        vector<vector<char> > v2d;
        // Create a vector with 5 elements
        vector<char> v2(5, '?');
        // Create a vector of 3 elements. 
        vector<vector<char> > v2d2(3, v2);
        // Print out the elements
        cout << "Before Vector Update" << endl;
        for (int i = 0; i < v2d2.size(); i++) {
            for (int j = 0; j < v2d2[i].size(); j++)
                cout << v2d2[i][j] << " ";
            cout << endl;
        }
        cout << "" << endl;
        /* Does not work as expected
        cout << "Vector Update" << endl;
        for (int i = 0; i < v2d2.size(); i++) {
            for (int j = 0; j < v2d2[i].size(); j++)
            {
                if (v2d[i] == '?');
                (v2d[i] = 'x');
            }
        }
        */
        cout << "" << endl;
        cout << "After Vector Update" << endl;
        for (int i = 0; i < v2d2.size(); i++) {
            for (int j = 0; j < v2d2[i].size(); j++)
                cout << v2d2[i][j] << " ";
            cout << endl;
        }
system("pause > NULL");
return 0;
}

当我尝试编译代码时,我收到下面的错误消息。

IntelliSense:没有运算符"=="匹配这些操作数操作数类型为:std::vector>,std::allocater>>==char Project3\Source.cpp 77 16 Project3

我认为这是容器在更新正确的行和列时出现的问题。任何帮助都将不胜感激。

感谢

有一些错误,请与您的原始代码进行比较:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
  // An empty vector of vectors
  vector<vector<char> > v2d;
  // Create a vector with 5 elements
  vector<char> v2(5, '?');
  // Create a vector of 3 elements. 
  vector<vector<char> > v2d2(3, v2);
  // Print out the elements
  cout << "Before Vector Update" << endl;
  for (int i = 0; i < v2d2.size(); i++) {
    for (int j = 0; j < v2d2[i].size(); j++)
      cout << v2d2[i][j] << " ";
    cout << endl;
  }
  for (int i = 0; i < v2d2.size(); i++) {
    for (int j = 0; j < v2d2[i].size(); j++)
      if (v2d2[i][j] == '?')
        v2d2[i][j] = 'x';
  }
  cout << "After Vector Update" << endl;
  for (int i = 0; i < v2d2.size(); i++) {
    for (int j = 0; j < v2d2[i].size(); j++)
      std::cout << v2d2[i][j] << " ";
    cout << endl;
  }

  return 0;
}

看看您的注释代码:

cout << "Vector Update" << endl;
for (int i = 0; i < v2d2.size(); i++) {
    for (int j = 0; j < v2d2[i].size(); j++)
    {
        if (v2d[i] == '?'); // <------
        (v2d[i] = 'x');
    }
}

if语句后面有一个分号,这意味着如果该语句为true,则不会执行任何操作。新手失误。

许多人认为,不总是在if-语句和其他需要括号的类似情况下使用括号是一种糟糕的做法,因为

您应该有:

        if (v2d[i][j] == '?'){
            v2d[i][j] = 'x';
        }
    cout << "Vector Update" << endl;
    for (int i = 0; i < v2d2.size(); i++) {
        for (int j = 0; j < v2d2[i].size(); j++)
        {
            if (v2d[i][j] == '?')
                v2d[i][j] = 'x';
        }
    }

您没有正确访问2d矢量,应该使用v2d[i][j]。