本文介紹了c ++ sort 跟蹤索引的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
您是否有一些有效的例程來返回帶有數(shù)組中已排序元素索引的數(shù)組?我認(rèn)為使用 stl vector
存在一些方便的方法.你已經(jīng)實現(xiàn)了一個沒有stl的高效算法,或者你有偽代碼或C++代碼的參考嗎?
Do you have some efficient routine for returning array with indices for sorted elements in a array? I think that some convenient way exists using stl vector
. Do you have already implemented an efficient algo without stl, or do you have a reference to pseudo code or C++ code?
推薦答案
使用 C++11,以下應(yīng)該可以正常工作:
Using C++11, the following should work just fine:
template <typename T>
std::vector<size_t> ordered(std::vector<T> const& values) {
std::vector<size_t> indices(values.size());
std::iota(begin(indices), end(indices), static_cast<size_t>(0));
std::sort(
begin(indices), end(indices),
[&](size_t a, size_t b) { return values[a] < values[b]; }
);
return indices;
}
這篇關(guān)于c ++ sort 跟蹤索引的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!