正在将指针从数组值存储到原始数组索引位置

Storing pointer from array value to original array index location

本文关键字:数组 原始 索引 位置 存储 指针      更新时间:2023-10-16

我正在对数组进行排序,需要将指针从这些值存储到原始索引位置。建议的方法是什么?

简化示例:

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