这是我的代码
typedef std::pair<unsigned long, unsigned long> link;
std::map<link, double> container;
我想做的是计算从 X 到 Y 的距离,并将其存储在容器中作为 container.insert(std::make_pair(link, distance)); 并说现在我必须计算从 Y 到 X 的距离,而不是重做整个计算,从容器中获取存储的值,即..,链接和距离。
我目前的实现只针对 (X,Y)
std::map<link, double>::iterator It = container.begin();
std::pair<unsigned long, unsigned long> k = link(X,Y);
It = container.find(K);
if(It != container.end()) { distance = It->second; }
else { /* distance = /* complex calc */ container.insert(std::make_pair(k,distance)); }
我怎样才能使它泛化,使 link(X,Y) 和 link(Y,X) 被视为相同?
最佳答案
为您的 map 使用不同的关键比较器,例如:
bool link_compare(link lhs, link rhs) // note: parameters taken by value
{
if (lhs.first > lhs.second) std::swap(lhs.first,lhs.second);
if (rhs.first > rhs.second) std::swap(rhs.first,rhs.second);
return lhs < rhs;
}
std::map<link, double, bool(*)(link,link)> container(link_compare);
不过我认为,您应该考虑将 link
设为一个单独的类,使用特定于它的数据成员名称,而不是通用的 first
和 second
。 std::pair
,在我看来,当您必须将它们作为单个对象传递时,可以快速解决包含不相关数据的问题。你所拥有的显然是非常相关的数据。仅仅因为 std::pair
恰好能够保存正确的数据成员,并不意味着您应该使用它。
关于c++ - 将两个 std::pair(X,Y) 视为与 std::pair(Y,X) 相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15444598/