如何对包含通过索引相互关联的数据的多个数组进行排序

How to sort multiple arrays that contain data associated to each other via index

本文关键字:数据 排序 数组 关联 包含通 索引      更新时间:2023-10-16

我有一组包含城市、国家、纬度和纬度的数组。 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]);
}
如何同时对纬度和

经度数组进行排序,以找到列表中所有其他纬度的最低或最高前五个,但同时又不会丢失与这些纬度和长度相关的城市和国家元素?

"同时不要失去与这些纬度和长度相关的城市和国家元素">

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

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

这个问题可能会帮助你:如何使用 std::sort 与结构向量并比较函数?

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

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;
});