我正在对数组进行排序,需要将这些值的指针存储到原始索引位置。建议的方法是什么?
简化示例:
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时,我需要知道这是第一个数组中的第二个元素。我该怎么做呢?
答案 0 :(得分: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]);
}
答案 1 :(得分:0)
我想可能会创建一个指针数组并对指针数组(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;
}
答案 2 :(得分:0)
只是想在这里添加更像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;
}