c++ - 从文件中读取数据对

标签 c++ vector std-pair

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

#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 中的元素,而不是整数。您现在可以访问 firstsecond

如果您不能使用基于范围的 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/

相关文章:

R - 通过矢量计数并刷新某个值?

r - 从 R 中的向量创建矩阵

c++ - 为什么 pair 在初始化时不需要类型

c++ - C++ 中的对是否有 NULL 等价物?

c++ - OpenCV ArUco标记,如何获得它们的中心?

c++ - 调试器问题

c++ - openCV imread 限制大或巨大的图像 Mat bug #3258

java - 如何在字节数组 Java 中表示 header 值和实际消息?

c++ - 跨窗

c++ - 在 C++ 中对一对 vector 进行排序