我正在尝试在2D矢量中搜索char,即'?'并用'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&gt;,std :: allocator&gt;&gt;&gt; == char Project3 \ Source.cpp 77 16 Project3
我认为容器在更新正确的行和列时存在问题。任何帮助将不胜感激。
谢谢
答案 0 :(得分:1)
有一些错误,请与原始代码进行比较:
#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;
}
答案 1 :(得分: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
语句后面有一个分号,表示如果语句为真,则不会执行任何操作。菜鸟错误。
许多人认为bad practice不要总是使用括号if
- 语句和需要它们的其他类似情况,因为像这样的问题
答案 2 :(得分:0)
你应该:
if (v2d[i][j] == '?'){
v2d[i][j] = 'x';
}
答案 3 :(得分: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][j] == '?')
v2d[i][j] = 'x';
}
}
您没有正确访问2d向量,应该使用v2d [i] [j]。