首页 > 解决方案 > 排序 std::reference_wrapper 数组时出现问题,引用向量

问题描述

我对此有点坚持,我正在使用 std::array 将引用包装器存储到向量。我试图使用 std::sort 按向量的大小对它们进行排序,但由于我不太确定的原因,即使在阅读了编译器错误之后也是如此。我是否必须使用另一个排序函数,因为似乎 std::sort 实现使用了无法在引用包装器上使用的操作。

谢谢 :)

编译器资源管理器版本

    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <vector>
    #include <array>
    #include <string>
    #include <sstream>
    #include <utility>
    
    
    void findSum(const std::vector<int>& vec1, const std::vector<int>& vec2, const std::vector<int>& vec3)
    {    
        std::array<std::reference_wrapper<const std::vector<int>>, 3> vecRefs{vec1, vec2, vec3};
        
        std::sort(std::cbegin(vecRefs), std::cend(vecRefs), [](const auto vecA, const auto vecB) -> bool {
                return vecA.get().size() > vecB.get().size(); //descending order
            });
    
        //vecRefs should now be storing reference wrappers to the vectors with sizes in descending order
    
        //print longest vec first, shortest vec last
        for (const auto vec : vecRefs)
        {
            for (const auto val : vec.get())
            {
                std::cout << val << ' ';
            }
            std::cout << '\n';
        }
    
        //TODO: rest of function(the bit before this can be made into a function)
    }

标签: c++stdreference-wrapper

解决方案


这是因为std::cbeginstd::cendstd::sort.
这意味着,您无法更改数组的顺序!
只需将其替换为std::beginstd::end这样:

std::sort(std::begin(vecRefs), std::end(vecRefs), [](const auto vecA, const auto vecB) -> bool {
        return vecA.get().size() > vecB.get().size();
        });

推荐阅读