从文件中读取数据对

问题描述 投票:1回答:2

我试图使用以下代码从文件中读取数据对。

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


using namespace std;

int main()
{
//**** Opening data file ****   

    ifstream infile;
    infile.open("reg_data_log.inp");

    if (infile.is_open())
    {
        cout << "File successfully open" << endl;

    }
    else
    {
    cout << "Error opening file";
    }

//**** Reading data ***

    vector<pair<double, double> > proteins;

    pair<double, double> input;

    while (infile >> input.first >> input.second) 
    {
        proteins.push_back(input);
    }

//**** Show data in screen ****

    cout << "Proteins analized: " << proteins.size() << endl;

    for(unsigned int i=0; i<proteins.size(); i++)
    {
        cout << i.first << ", " << i.second << endl;
    }

}

编译时我有以下消息

“65:13:错误:在'i'中请求成员'first',这是非类型'unsigned int'” “65:13:错误:在'i'中请求成员'first',这是非类型'unsigned int'”

我无法理解这个问题。有人可以帮忙吗?

c++ vector std-pair
2个回答
2
投票

进一步了解你的循环

for(unsigned int i=0; i<proteins.size(); i++)
{
    cout << i.first << ", " << i.second << endl;
}

您正在尝试访问整数值first的属性i。整数没有该属性,它是pair对象的属性。

我认为你在迭代使用迭代器和索引之间感到困惑。简单的解决方法是使用基于for循环的范围,如评论中已经建议的那样。

for(auto d: proteins)
{
    cout << d.first << ", " << d.second << endl;
}

现在你所拥有的是vector中的元素而不是整数。您现在可以访问firstsecond

如果你不能使用基于范围的for循环和auto,那么你可以使用旧的迭代器来循环方式。

for(vector<pair<double, double> >::iterator it = proteins.begin();
    it != proteins.end();
    ++it)
{
    cout << it->first << ", " << it->second << endl;
}

而其他人已经发布了如何使用索引来完成它,所以我在此不再重复。


1
投票

正如qazxsw poi在他的评论中提到的,实际上你引用的是int而不是对类型。以下循环很可能会解决您的问题:

John Mopp

我还没有测试过,但我相信这可以解决你的问题。

© www.soinside.com 2019 - 2024. All rights reserved.