我正在對數組進行排序,並且需要將這些值的指針存儲到原始索引位置。推薦的方法是什麼?從數組值存儲指針到原始數組索引位置
簡化的例子:
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時,我需要知道,這是第一陣列中的第二個元素。我會怎麼做呢?
我正在對數組進行排序,並且需要將這些值的指針存儲到原始索引位置。推薦的方法是什麼?從數組值存儲指針到原始數組索引位置
簡化的例子:
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;
}
也許如果efficency是不是真的有問題,你可以進行手動排序,並使用「指針」(這不是真正的指針) 像這樣的另一個數組:
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;
}
創建引用數組,和引用排序? –
@JoelCornett我相信該標準禁止引用數組。 – NathanOliver
@Joel:確切地說,沒有辦法創建引用數組,只有'std :: ref'數組。 – GingerPlusPlus