【问题标题】:How to sort multiple arrays that contain data associated to each other via index如何对包含通过索引相互关联的数据的多个数组进行排序
【发布时间】:2013-10-17 07:34:54
【问题描述】:

我有一组包含城市、国家、纬度和纬度的数组。 c++语言。

ifstream file("worldcities.csv");
getline(file, temporay);
//inputs the file into 4 arrays for each catergories
for (i=0;getline(file,(cities[i]),',');i++)
{
getline(file, countries[i], ',');
getline(file, latitude[i], ',') ;
getline(file, longitude[i]);
}

我如何同时对纬度和经度数组进行排序,以找到列表中所有其他人中最低或最高的前五个,但同时不丢失那些经纬度所在的城市和国家的元素有关联吗?

【问题讨论】:

  • 如果你将城市、国家、纬度、经度组合成一个结构或类,然后使用单个数组(或者更好,向量)会容易得多。
  • 我该怎么做?还没有真正使用矢量或结构。
  • 最好的解决方案是“不要使用并行数组”:将所有信息聚合到一个记录列表(或向量)中。
  • @user2770315 你谷歌“c(++) 结构教程”(或阅读初学者的书),然后你谷歌“std::vector 文档”,你会做得很好。

标签: c++ arrays sorting file-io vector


【解决方案1】:

“同时不丢失与经纬度相关的城市和国家的元素”

当这些是属于一起的值时,为什么不将它们捆绑在一个对象中? IE。:
struct Location {
    std::string city, country;
    double lng, lat;
};

一旦将所有位置加载到std::vector<Location> 中,您就可以定义自己的比较器并使用std::sort

这个问题可能对你有帮助:How to use std::sort with a vector of structures and compare function?

【讨论】:

  • 对如何将其从 cvs 文件加载到 struct 然后 intilizing 变量感到困惑。
  • @user2770315: This question 在我寻找“从 C++ 中的 CSV 文件读取值”时第一次被点击。
【解决方案2】:

如果您创建一个将数据保存在一起的类或结构(而不​​是通过数组索引关联它们),您会发现管理起来要容易得多:

struct Details
{
    std::string city;
    std::string country;
    double latitude;
    double longitude;
};

struct csv_reader : std::ctype<char>
{
    csv_reader() : std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask> rc(table_size, std::ctype_base::mask());
        rc[','] = std::ctype_base::space;
        rc['\n'] = std::ctype_base::space;
        return &rc[0];
    }
};

// in your program logic
std::ifstream fin("worldcities.csv");
std::vector<Details> vecDetails;
std::string line;
csv_reader reader;
while (std::getline(fin, line))
{
    std::istringstream iss(line);
    iss.imbue(std::locale(std::locale(), &csv_reader));
    Details d;
    iss >> d.city >> d.country >> d.latitude >> d.longitude;
    vecDetails.push_back(d);
}

// to sort by latitude
std::sort(vecDetails.begin(), vecDetails.end(), [](const Details& l, const Details& r)
{
    return l.latitude < r.latitude;
});

【讨论】:

  • locale 和 cvs 阅读器的库是什么?它给了我一个错误。
  • error C2275: 'main::csv_reader' : 非法使用这种类型作为表达式
  • 你必须包含&lt;locale&gt; ...我错过了一个错字。固定。
  • iss.imbue(std::locale(std::locale(), csv_reader));
  • main::csv_reader' : 非法使用这种类型作为表达式
猜你喜欢
  • 2020-11-02
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 2011-07-26
  • 1970-01-01
  • 2012-12-17
  • 2013-12-03
  • 2013-06-09
相关资源
最近更新 更多