我正在尝试使用以下代码从文件中读取数据对。
#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: error: request for member ‘first’ in ‘i’, which is of non-class type ‘unsigned int’"
"65:13: error: request for member ‘first’ in ‘i’, which is of non-class type ‘unsigned int’"
我无法解决这个问题。有人可以帮忙吗?
最佳答案
进一步观察你的循环
for(unsigned int i=0; i<proteins.size(); i++)
{
cout << i.first << ", " << i.second << endl;
}
您正在尝试访问整数值 i
的属性 first
。整数没有该属性,它是 pair
对象的属性。
我认为您对使用迭代器和索引进行迭代感到困惑。简单的解决方法是使用基于范围的 for 循环,正如评论中已经建议的那样。
for(auto d: proteins)
{
cout << d.first << ", " << d.second << endl;
}
现在您拥有的是 vector 中的元素,而不是整数。您现在可以访问 first
和 second
。
如果您不能使用基于范围的 for 循环和 auto
,那么您可以使用旧的迭代器 for 循环方式。
for(vector<pair<double, double> >::iterator it = proteins.begin();
it != proteins.end();
++it)
{
cout << it->first << ", " << it->second << endl;
}
其他人已经发布了如何使用索引来完成它,所以我不会在这里重复。
关于c++ - 从文件中读取数据对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43715414/