如何对包含通过索引相互关联的数据的多个数组进行排序
How to sort multiple arrays that contain data associated to each other via index
我有一组包含城市、国家、纬度和纬度的数组。 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;
});
相关文章:
- 如何对点云数据进行排序
- 如何使用 QSortFilterProxyModel::sort 对 Qlist 中的数据进行排序
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 使用选择排序对数组数据结构进行排序,但它不起作用
- 为什么我的代码没有对数组中第二个索引上的数据进行排序?
- 使用 QSortFilterProxyModel 对 Qml ListView 的数据进行排序
- 读取 C++ 中的 txt 数据,展开为行或列并排序
- C++ 从文件中获取数据时使用 strcpy 和 strcmp 按字母顺序对数组进行排序?
- 存储在 std::map/std::set 中,与在存储所有数据后对向量进行排序
- 尝试创建排序的动态列表(数据结构)
- 固定大小的容器,其中元素被排序,并可以为C 中的数据提供原始指针
- 排序算法,使用模板按内部数据对对象进行排序
- 对多个数据成员进行排序
- 递归定义数组中的数据对齐和排序
- 如何修复输出显示,以便显示正确排序的数据
- 为什么我的气泡排序不适用于双精度数据类型?
- 气泡排序不传递数据或不起作用
- 使用 stl::map 和 stl::unordered_map 对包含大量重复元素的数组数据进行排序
- 数据排序依据是哪一列,QTableWidget
- 寻找更好的数据排序方法