c++ - 排序 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)
}
解决方案
这是因为std::cbegin
您std::cend
在std::sort
.
这意味着,您无法更改数组的顺序!
只需将其替换为std::begin
和std::end
这样:
std::sort(std::begin(vecRefs), std::end(vecRefs), [](const auto vecA, const auto vecB) -> bool {
return vecA.get().size() > vecB.get().size();
});
推荐阅读
- java - “没有主题替代 DNS 名称匹配
发现”使用 RestTemplate 时出错 - java - 子树JPQL的意外结束
- ssms - 为什么 17.8.1 版的 SSMS-setup-ENU 没有运行?
- php - 在php中从字符串中搜索数字
- python - python实例化一个嵌套类
- c# - Selenium C# - 尽管网站可以浏览,但 HttpWebRequest 始终返回 404
- javascript - 在 Javascript 中扩展对象
- javascript - 在括号之间指定参数和不指定参数有什么区别?
- dynamics-crm - 如何在 CRM Dynamics 中构建自定义页面?
- ios11 - 第一个表格单元格被 MFMessageComposeViewController 上的联系人输入字段覆盖