替换2D矢量C++中的数据
Replace data in 2D vector C++
我正试图在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]。
相关文章:
- 防止主数据类型C++的隐式转换
- 用于访问容器<T>数据成员的正确 API
- 嵌套在类中时无法设置成员数据
- 使用流处理接收到的数据
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在cuda线程之间共享大量常量数据
- C++将文本文件中的数据读取到结构数组中
- 如何在C++中序列化结构数据
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 在c代码之间共享数据的最佳方式
- 链表,反向函数,数据结构
- 数据成员SFINAE的C++17测试:gcc vs clang
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何对点云数据进行排序
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 在运行时处理类型擦除的数据-如何不重新发明轮子