如果 a==b 则保存成本最低的那个
你不能使用 std::set :a==b 意味着 a<b 和 b<a 是假的,所以当 a 和 b 有相同的 row 和 cols operator< 必须返回 false 并且不考虑 cost
要获得预期的行为,您必须实现自己的set,而不仅仅是使用operator< 进行排序/插入。
按路径成本排序
我想你的意思是按成本订购
使用 std::set 和 operator< 我们可以想到:
bool operator <(const node & rhs) const {
// to satisfy a==b only if row and cols are equal
if ((row == rhs.row) && (cols == rhs.cols))
return false;
return (cost < rhs.cost) ||
((cost == rhs.cost) &&
((row < rhs.row) || ((row == rhs.row) && (cols < rhs.cols))));
}
但这是错误的,例如
#include <set>
#include <iostream>
struct node{
int row;
int cols;
int cost;
bool operator <(const node & rhs) const {
// to satisfy a==b only if row and cols are equal
if ((row == rhs.row) && (cols == rhs.cols))
return false;
return (cost < rhs.cost) ||
((cost == rhs.cost) &&
((row < rhs.row) || ((row == rhs.row) && (cols < rhs.cols))));
}
};
int main()
{
const node a[] = { {3,2,3} , {3,2,2}, {4,3,2}, {7,2,3}, {3, 2, 9} };
std::set<node> s;
for (size_t i = 0; i != sizeof(a)/sizeof(*a); ++i)
s.insert(a[i]);
for (auto x : s)
std::cout << '(' << x.row << ' ' << x.cols << ' ' << x.cost << ')' << std::endl;
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall s.cc
pi@raspberrypi:/tmp $ ./a.out
(4 3 2)
(3 2 3)
(7 2 3)
(3 2 9)
set 包含 3 2 3 和 3 2 9,即使它们必须被视为相等。
operator< 是错误的,因为在将 3 2 3 和 3 2 9 与其他值进行比较时它不一致:7 2 3 小于 3 2 9 但不小于 3 2 3
a==b 仅当 row 和 cols 相等时
暗示排序必须只考虑row和cols,但cost必须不使用 p>
例如
#include <set>
#include <iostream>
struct node{
int row;
int cols;
int cost;
bool operator <(const node & rhs) const {
return (row < rhs.row) || ((row == rhs.row) && (cols < rhs.cols));
}
};
int main()
{
const node a[] = { {3,2,3} , {3,2,2}, {4,3,2}, {7,2,3}, {3, 2, 9} };
std::set<node> s;
for (size_t i = 0; i != sizeof(a)/sizeof(*a); ++i)
s.insert(a[i]);
for (auto x : s)
std::cout << '(' << x.row << ' ' << x.cols << ' ' << x.cost << ')' << std::endl;
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall s.cc
pi@raspberrypi:/tmp $ ./a.out
(3 2 3)
(4 3 2)
(7 2 3)
pi@raspberrypi:/tmp $
尊重预期的平等,但不涉及成本
来自 C++11(感谢@PaulMcKenzie 的评论):
bool operator <(const node & rhs) const {
return std::tie(row, cols) < std::tie(rhs.row, rhs.col);
}
当需要考虑很多领域时非常实用