如何在不修改范围的情况下按降序迭代范围

问题描述 投票:0回答:1

有人可以告诉我我做错了什么吗?我正在尝试按降序访问元素。我无法修改输入数据,因此

std::sort
不是一个选项。

我尝试使用

std::max_element
,但是当它等于
std::begin()
时,不知怎的我找不到当前最大值的最小值。这是为什么?

const std::vector<int> v{2, 1, 4, 5, 0, 6, 4, 3, 2};
auto max = std::max_element(v.begin(), v.end());
auto min = std::min_element(v.begin(), v.end());
auto tmp = std::begin(v);

while(*max != *min)
{
    tmp = std::max_element(v.begin(), v.end(),
        [max](const auto& item1, const auto& item2)
        {
            return item2 < *max && item1 < item2;
        });
    max = tmp;        
}
c++ std
1个回答
0
投票

只需复制并排序即可。这比尝试在不修改原始容器的情况下进行内联操作要高效得多,特别是对于较大的数据集。

#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>

std::vector<int> descending_order(const std::vector<int>& vec)
{
    auto copy = vec;
    std::sort(copy.begin(), copy.end(), std::greater<int>());
    return copy;
}

int main()
{
    const std::vector<int> v{2, 1, 4, 5, 0, 6, 4, 3, 2};
    auto correct_order = descending_order(v);

    // prints '6 5 4 4 3 2 2 1 0 '
    for (auto val : correct_order) {
        std::cout << val << " ";
    }
    std::cout << "\n";
}
© www.soinside.com 2019 - 2024. All rights reserved.