将数据插入矢量

Insert data into vector

本文关键字:插入 数据      更新时间:2023-10-16

我有一个.txt文件,其中的数据格式如下:

1.23,2.34,3.45
4.56,5.67,6.78

如何在矢量中插入数字

vector[1]={1.23,4.56,...}
vector[2]={2.34,5.67,...}
vector[3]={3.45,6.78,...}

代码

ifstream in("data.txt");
vector<vector<int> > v;
if (in) {
    string line;
    while (getline(in,line)) {
        v.push_back(std::vector<int>());
        stringstream split(line);
        int value;
        while (split >> value)
            v.back().push_back(value);
    }
}

代码中存在多个问题

  1. 您的内部vector应该是floatdoublevector,而不是int

  2. 您的value变量也应该是floatdouble

  3. 阅读时你需要越过分隔符(逗号)。

  4. 您需要创建与每行中的值一样多的内部向量。我在下面通过使用一个布尔first变量来实现这一点——我使用它来确保只在读取第一行时创建向量。

  5. push_back到的内部向量的索引与被推回的行上的值的列编号相同。我使用变量col来计算当前在一行上读取的列编号。

您需要与列数一样多的内部向量。每个内部向量的成员数与文件中的行数一样多。

ifstream in("data.txt");
vector<vector<double> > v;
bool first = false;
if (in) 
{
    string line;
    while (getline(in,line)) 
    {
        istringstream split(line);
        double value;
        int col = 0;
        char sep;
        while (split >> value)
        {
            if(!first)
            {
                // Each new value read on line 1 should create a new inner vector
                v.push_back(std::vector<double>());
            }
            v[col].push_back(value);
            ++col;
            // read past the separator                
            split>>sep;
        }
        // Finished reading line 1 and creating as many inner
        // vectors as required            
        first = true;
    }
}