gpt4 book ai didi

c++ - STL 或 BOOST 是否提供任何干净的方法来获取排序顺序而无需重新排序原始序列?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:11:39 27 4
gpt4 key购买 nike

例如,我想找到 vector 的排序顺序,而不需要重新排序 vector 。

我可以想到几种方法来做到这一点,我想知道我是否缺少一些内置的 STL 或 BOOST 方法来做到这一点。

我想如果该功能可用,代码最终会看起来像这样:

std::vector<float> unsortedSeq;
unsortedSeq.push_back( 1.1 );
unsortedSeq.push_back( 1.0 );
unsortedSeq.push_back( 0.5 );
unsortedSeq.push_back( 1.2 );
unsortedSeq.push_back( 1.15 );

std::list<std::size_t> sortOrder;

std::sort_indices( unsortedSeq.begin(), unsortedSeq.end(), sortOrder.begin() );

BOOST_FOREACH( std::size_t index, sortOrder )
{
std::cout << index << "\n"
}



2
1
0
4
3

有谁知道任何 STL 或 BOOST-sims 可以像显示的那样简单地完成我所问的事情?

最佳答案

std::vector<float> v;
// filled somewhere else

std::vector<std::size_t> indices(v.size());
// iota is from <numeric>, C++0x
std::iota(indices.begin(), indices.end(), 0);

std::sort(indices.begin(), indices.end(), [&v](std::size_t left, std::size_t right)
{
return v[left] < v[right];
});

关于c++ - STL 或 BOOST 是否提供任何干净的方法来获取排序顺序而无需重新排序原始序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6499413/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com