簡體   English   中英

將二維矩陣文件復制到大小未知的二維向量中

[英]copying 2d matrix file into a 2d vector with unknown size

我有一個由未知行組成但有 2 列的文件,我想將其讀入二維向量,但我無法實現,因為我的代碼一直跳過第一列,我不知道為什么

我寫的代碼如下:

#include <iostream>
#include <fstream>
#include <vector>
// this is for file handleing

using namespace std;



int main()
{
    ifstream fp("test3_r.txt");

    std::string token;


    vector< vector<int> > vt1;


    int x = 0;

    char split_char = ' ';

    
    int i =0;

    std::vector<int> inner_vector;

    while (std::getline(fp, token,split_char))
    {
        inner_vector.push_back(stoi(token));
        if(i%2==1)
        {
            vt1.push_back(inner_vector);
            inner_vector.clear();
        }
        i++;
    

    }



    for (int i = 0; i < vt1.size(); i++)
{
    for (int j = 0; j < vt1[i].size(); j++)
    {
        cout << vt1[i][j];
        cout << " ";

    }
    std::cout<<"\n";
}

    fp.close();
    return 0;
} 

我的輸入文件的例子:

0 3
0 7
0 10
0 16
0 23
0 25
0 26
0 28
0 30
1 17
1 18
2 18
2 25
3 0
3 10
3 11
3 16
3 19
3 25
3 28
3 31
4 10
4 18
4 25
5 0
5 9
5 10
5 11
5 16
5 18
5 23
5 25
5 28
6 0
6 1
6 4
6 9
6 10
6 11
6 12
6 15
6 16
6 18
6 23
6 25
6 27
6 28
6 30
7 0
7 18
7 22
7 23
7 25 

我得到的 output 是:

0 3 
7 10 
16 23 
25 26 
28 30 
17 18 
18 25 
0 10 
11 16 
19 25 
28 31 
10 18 
25 0 
9 10 
11 16 
18 23 
25 28 
0 1 
4 9 
10 11 
12 15 
16 18 
23 25 
27 28 
30 0 
18 22 
23 25  

這不是我想要的。 任何幫助表示贊賞

問題出在線上

inner_vector.push_back(stoi(token));

你以為你在做的是傳遞諸如“0”,然后“3”,然后“0”等東西。但事實是你傳遞了諸如“0”,“3\n0”,“7\n0”之類的東西. getline 忽略結束線,當將類似“ 3\n0” 的內容傳遞給 stoi 時,它返回 3 並切斷特殊字符后的所有內容。 我的實現如下:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
    ifstream fp("f.txt");

    string token;

    vector< vector<int> > vt1;

    while(getline(fp, token)){ // if you are given the size just do fp >> 
        vector<int> cols(2);
        stringstream ss(token);

        ss >> cols[0] >> cols[1];
        vt1.push_back(cols);
        cols.clear();
    }

    for (auto &i : vt1){
        cout << i[0] << ' ' << i[1] << endl;
    }

} 

據我所知,您無法讓 getline 分隔多個字符,因此這是下一個最佳解決方案。

你的方法過於復雜了。

如果你的向量只會有 2 個元素,那么使用std::vector來保存它們就太過分了。 您可以輕松地使用std::pairstd::tuple或實現您自己的 class Vector2D來保存組件。 使用后者將允許您執行以下操作:

std::vector<Vector2D> vt1;
vt1.assign(std::istream_iterator<Vector2D>(fp), std::istream_iterator<Vector2D>());

如果出於某種原因必須使用向量的向量來保存數據,您仍然可以以更簡單的方式完成它:

int x, y;
while (fp >> x >> y)
{
    std::vector<int> t {x, y};
    vt1.push_back(t);
}

沒有必要讀入行,然后嘗試解析行外的整數。 提取運算符已經為您完成了。

只是讓你知道你不需要使用 std:: 當你有“使用命名空間 std;”時,使用命名空間的全部意義在於避免 std::

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM