使用范围允许我减少样板文件,所以这很好,但我找不到按升序或降序排序的方法。以下代码段编译得很好(g++ 10.2.0)并且投影确实简化了代码,不需要 lambda。
struct Player {
double score_;
string name_;
};
vector<Player> players{
{10.0, "Thorin"}, {20.0, "Bombur"}, {15.0, "Bofur"}, {5.0, "Bifur"},
{ 2.0, "Balin"}, {25.0, "Kili" }, {23.0, "Fili"}, {4.0, "Dwalin"}
};
std::ranges::sort(players, std::ranges::less{}, &Player::score_ );
for(auto const &player : players) {
cout << "Name = " << std::left << setw(10) << player.name_
<< " Score = " << player.score_ << endl;
}
Run Code Online (Sandbox Code Playgroud)
现在我需要一个布尔控制升序或降序排序。
我想写一个这样的简单语句:
std::ranges::sort(players, sort_ascending ? std::ranges::less() : std::ranges::greater() , &Player::score_);
Run Code Online (Sandbox Code Playgroud)
但是std::ranges::less和std::ranges::greater没有相同的类型,所以三元运算符将不起作用。
error: operands …Run Code Online (Sandbox Code Playgroud) 在下面的程序中,我将一些信息存储在哈希表(std :: unordered_map)中,键是RectData类的对象,关联的值是元组<uint,RectData,enum>和自定义KeyHash和KeyEqual定义.
在没有默认构造函数的情况下插入<key,value>对会在gcc 4.9.2中出现两页错误.第一个错误的行是:
visited_info[rect0] = info0;
Run Code Online (Sandbox Code Playgroud)
我用MSVC++ 12.0仔细检查过,我也有错误信息.
当我添加默认构造函数时,编译是正常的,并且在运行时调用默认构造函数.我无法理解为什么RectData类需要默认构造函数?
使用[]运算符从哈希表中检索数据也需要在编译时使用默认构造函数,但是在运行时不会调用它,为什么?
auto info = visited_info[rect];
Run Code Online (Sandbox Code Playgroud)
注意:使用visited_info.emplace()和visited_info.find()更改代码可以解决问题,但不会回答问题.
谢谢你的回答.
完整代码如下.
#include <boost/functional/hash.hpp>
#include <tuple>
#include <vector>
#include <unordered_map>
#include <iostream>
using uint = unsigned int;
enum class Direction : int { left = 0, right = 1, up = 2, down = 3, null = 4 };
class RectData {
public:
RectData(uint width, uint height)
: width_(width), height_(height), datas_(width * height, 0) {
total_ = width_ * height_;
}
// A …Run Code Online (Sandbox Code Playgroud)