c++ - 在 C++ 排序中指定比较函数的参数
问题描述
我的问题是 C++ 排序函数中的比较函数如何接受参数。如果我想对数组进行排序但又想保留元素的索引,我想根据实际数组中的元素对索引数组进行排序。问题是我无法找到如何将参数传递给比较函数。假设数组是 3 5 4 2 索引是 0 1 2 3 。我想要索引数组输出 3 0 2 1 ,即 2 3 4 5 。我怎样才能使用排序功能做到这一点。
解决方案
一种方法:
vector<int> data{ 3, 5, 4, 2 },
index{ 0, 1, 2, 3 };
sort(index.begin(), index.end(), [&data](int i, int j) { return data[i] < data[j]; });
for (int i : index)
{
cout << i << ' ';
}
推荐阅读
- python - 只有单个输入时如何处理 MinMaxScaler?
- aws-sdk - Amazon Connect 自动拨出电话
- android - 错误:包 com.bumptech.glide.request.animation 不存在
- javascript - SecurityError:操作不安全。php
- sql - SQL Server:从包含 json 字符串的 nvarchar(max) 变量中获取所有字符串出现(标签)
- jpa - 外键的列数错误
- c# - .net 核心视图模型提供路由参数
- javascript - 以编程方式在 JSTree 中创建文件夹结构
- android - 如何解决 Quickblox 中的“基本所需会话不存在”错误?
- python - 修复opencv python + ImageMagick中detectAndCompute的windows和linux结果不一致的问题