我试图使用以下代码从文件中读取数据对。
#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'”
我无法理解这个问题。有人可以帮忙吗?
进一步了解你的循环
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中的元素而不是整数。您现在可以访问first
和second
。
如果你不能使用基于范围的for循环和auto
,那么你可以使用旧的迭代器来循环方式。
for(vector<pair<double, double> >::iterator it = proteins.begin();
it != proteins.end();
++it)
{
cout << it->first << ", " << it->second << endl;
}
而其他人已经发布了如何使用索引来完成它,所以我在此不再重复。