[英]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.