正在将指针从数组值存储到原始数组索引位置
Storing pointer from array value to original array index location
我正在对数组进行排序,需要将指针从这些值存储到原始索引位置。建议的方法是什么?
简化示例:
float myArray[4] = {0.1, 0.4, 0.3, 0.2}
std::sort(myArray, myArray + 4, std::greater<float>());
结果:
{0.4, 0.3, 0.2, 0.1}
现在读0.4时,我需要知道这是第一个数组中的第二个元素。我该怎么做?
我想也许可以创建一个指针数组并对指针数组(lambda)进行排序。但不确定这样做对你是否有用。
#include <iostream>
#include <algorithm>
using namespace std;
int main(void) {
float myArray[4] = {0.1, 0.4, 0.3, 0.2};
float *myPointers[4];
for (int i = 0; i < 4; i++)
myPointers[i] = &myArray[i];
sort(myPointers, myPointers + 4, [&] (float *a, float *b) {
return *a > *b;
});
// myArray
for (auto f : myArray)
cout << f << endl;
cout << endl;
// myPointers
for (auto f : myPointers)
cout << *f << endl;
cout << endl;
// Check the address of elements
cout << (myArray == myPointers[3]) << endl;
cout << (myArray + 1 == myPointers[0]) << endl;
cout << (myArray + 2 == myPointers[1]) << endl;
cout << (myArray + 3 == myPointers[2]) << endl;
cout << endl;
// Indices of elements
cout << myPointers[0] - myArray << endl;
cout << myPointers[1] - myArray << endl;
cout << myPointers[2] - myArray << endl;
cout << myPointers[3] - myArray << endl;
return 0;
}
如果效率不是真正的问题,您可以执行手动排序并使用另一个"指针"数组(它们不是真正的指针)像这样的东西:
int i, j;
float myArray[4] = {0.1, 0.4, 0.3, 0.2};
int index[4] = {0, 1, 2, 3};
for (i=0; i<4; i++)
for (j=i+1; j<4; j++)
if (myArray[i] < myArray[j])
{
fswap(&myArray[i], &myArray[j]);
swap(&index[i], &index[j]);
}
只是想在这里放一些更像C++的东西
#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
using namespace std;
template<typename T, typename Cmp>
vector<pair<T,size_t>> sorted_with_indices(const vector<T> &vec, const Cmp &comparator) {
vector<pair<T,size_t>> sorted;
sorted.reserve(vec.size());
for (size_t i = 0; i < vec.size(); ++i) {
sorted.push_back(make_pair(vec[i], i));
}
auto cmp = [&](pair<T,size_t> a, pair<T,size_t> b) {
return comparator(a.first, b.first);
};
sort(begin(sorted), end(sorted), cmp);
return sorted;
}
int main() {
vector<float> numbers = {0.4, 0.1, 0.3, 0.2};
auto sorted = sorted_with_indices(numbers, greater<float>());
for (const auto& el : sorted) {
cout << el.first << ' ' << el.second << endl;
}
return 0;
}
相关文章:
- 将浮动的heightmap数组导出为16位原始值
- 复制后删除原始数组指针将前 3 个字节设置为 0
- 检查反向数组是否与原始数组相同
- C++将原始字符数组存储在元组中
- 如何将数组传递给函数,以便在更改该函数中的数组值时原始数组的值不会更改?
- 从原始指针(衰减的 C 样式数组)和大小生成范围::视图
- 如何在C++中将 std::vector 移动到原始数组中
- 头文件会导致函数调用后原始数组出现问题
- 初始化std :: unique_ptr作为原始数组指针的初始化
- std::string 参数是如何从原始字符数组文本传递的
- 原始数组和 std::array 在 clang++ 和 VC++ 上的不同迭代器行为
- 使用 Python、C++ 和 pybind11 返回并传递原始 POD 指针(数组)
- 从C 到C#调用INT []显示随机大数字,而不是原始数组成员
- 我可以使用std ::分配的分配的原始数组
- 使用 std::sort 和原始指针数组?
- 如何在C++的所有函数中编辑原始数组
- 如何在被调用后保留数组的原始值
- 排序后如何将二维数组重置为原始形式
- STL 算法 + c'tor 不再适用于指向 C 数组的原始指针,因为指向一个过去的末端
- 将数组的原始指针施放为unique_ptr