[英]Loading a Matrix into a 2D vector C++
I am new to using vectors in C++, my goal is to read a matrix from the text file and store them into a 2D vector, My code is as follows : 我是在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';
}
}
now for an input of say 现在输入意见
10101010
01010101
10101011
01011010
I get an output of 我得到的输出
10101010
1010101
10101011
1011010
ie everytime a 0 is encountered in the beginning of a line it is omitted. 即,每次在行的开头遇到0时,都会将其省略。 I believe the problem is in the statement while(split>>value), but I dont know how to code it in a better way.
我相信问题出在while(split >> value)语句中,但是我不知道如何以更好的方式对其进行编码。
Replace 更换
while (split >> value)
v.back().push_back(value);
with 与
for(int x=0; x<line.size(); x++){
v.back().push_back((int)line[x] - (int)'0'));
}
and remove your string stream completely. 并完全删除您的字符串流。
It seems as if you actually want to store bits, but somehow struggled with parsing a line containing, for example, 10101010
into a series of bits. 似乎您实际上想存储位,但是在某种程度上很难将包含
10101010
的行解析为一系列位。 If you know the maximum number of bits per line, you could use bitset<N>
, which provide an easy to use overload for operator >>
that can directly read in something like 10101010
. 如果知道每行的最大位数,则可以使用
bitset<N>
,它为运算符>>
提供了易于使用的重载,可以直接读取10101010
。 Hope it helps. 希望能帮助到你。
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.