如何将同一行中的值分组成一对? [英] How to group values from the same line into a pair?

查看:163
本文介绍了如何将同一行中的值分组成一对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个程序,它读取一个文本文件,该文件具有以下形式的数据集,并将每行的每2个整数置于一对中:

I am trying to write a program that reads a text file which has a data set in the form below and puts every 2 integers per line into a pair:

    1    2
    3    4
    5    6
    ... and so on

目前,我的主要代码的这一部分逐行读取文件,并将导入的字符串转换为整数一次一个数字,但我不知道如何将2个整数在每一行的时间,并把它们成对。最后,我想将所有对添加到单个集合。

Currently, this part of my main code reads the file line by line and converts the imported strings to integers one number at a time, but I am not sure how I would group 2 integers at a time in each line and put them in a pair. Ultimately, I want to add all the pairs to a single set.

    while (getline(fs, line))  {
            istringstream is(line); 
                while(is >> line) {                                             
               int j = atoi(line.c_str());
                cout << "j = " << j << endl;}} 


推荐答案

>

Following may help:

std::string line;
std::set<std::pair<int, int>> myset;
while (std::getline(fs, line)) {
    std::istringstream is(line);
    int a, b;
    if (is >> a >> b) {
        myset.insert({a, b});
    } else {
        throw std::runtime_error("invalid data");
    }
}

Live example

要考虑 1,5 5,1 相同,您可以使用:

To consider 1, 5 as identical as 5, 1, you may use:

struct unordered_pair_comp
{
    bool operator () (const std::pair<int, int>& lhs, const std::pair<int, int>& rhs) const
    {
        return std::minmax(lhs.first, lhs.second) < std::minmax(rhs.first, rhs.second);
    }
};

,因此您的 myset 变成 std :: set< std :: pair< int,int>,unordered_pa​​ir_comp> myset;

Live example

这篇关于如何将同一行中的值分组成一对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆