[英]Loading a Matrix into a 2D vector C++
我是在C ++中使用向量的新手,我的目标是从文本文件中读取矩阵并将其存储到2D向量中,我的代码如下:
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::ifstream in("input.txt");
std::vector<std::vector<int> > v;
if (in) {
std::string line;
while (std::getline(in, line)) {
v.push_back(std::vector<int>());
// Break down the row into column values
std::stringstream split(line);
int value;
while (split >> value)
v.back().push_back(value);
}
}
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v[i].size(); j++)
std::cout << v[i][j] << ' ';
std::cout << '\n';
}
}
现在输入意见
10101010
01010101
10101011
01011010
我得到的输出
10101010
1010101
10101011
1011010
即,每次在行的开头遇到0时,都会将其省略。 我相信问题出在while(split >> value)语句中,但是我不知道如何以更好的方式对其进行编码。
更换
while (split >> value)
v.back().push_back(value);
与
for(int x=0; x<line.size(); x++){
v.back().push_back((int)line[x] - (int)'0'));
}
并完全删除您的字符串流。
似乎您实际上想存储位,但是在某种程度上很难将包含10101010
的行解析为一系列位。 如果知道每行的最大位数,则可以使用bitset<N>
,它为运算符>>
提供了易于使用的重载,可以直接读取10101010
。 希望能帮助到你。
int main()
{
std::ifstream in("input.txt");
std::vector<std::bitset<8> >v;
if (in) {
std::bitset<8> bits;
while (in >> bits) {
v.push_back(bits);
}
}
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v[i].size(); j++)
std::cout << v[i][j] << ' ';
std::cout << '\n';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.