[英]Using comparator to sort set of unique pairs with different criterias for uniqueness and less than
首先,我試圖搜索類似的問題,但我沒有找到任何解釋我的問題可能是什么的回應。
問題如下:給定一組坐標為 (x,y,z) 的 N 個節點,使用第 4 個值 F 盡可能快地對它們進行排序。
為此,我想使用帶有自定義比較器的std::set
,因為它具有 O(log(N)) 復雜性。 我知道我也可以嘗試std::vector
和 std:: std::vector
上的std::sort
調用,但理論上是一個較慢的操作。
為什么這個? 因為我不斷地在集合中插入元素,更改 F值(這意味着我更改值並重新排序容器中的元素,我刪除並重新插入它)並且我想取 F 值較小的元素(這是容器前面的元素)。
但是讓我們 go 與std::set
問題。
坐標定義了唯一性,遵循嚴格的弱排序規則,這意味着如果a
和b
被認為是相同的 object
!comp(a,b) && !comp(b,a)
該問題與定義基於坐標的唯一性標准和基於 F 值的排序標准有關。 我不希望集合存儲具有相同坐標的兩個元素,但我希望它允許存儲具有不同坐標但 F 值相同的兩個元素
比較器還應滿足以下三個屬性:
x < x false
x < y true
意味着y < x false
x < y && y < z
意味着x < z true
因此,知道了所有這些屬性,我一直在使用以下示例實現:
class Node;
struct NodeComparator;
using NodePair = std::pair<Node *, int>;
using NodeSet = std::set<NodePair, NodeComparator>;
為了方便起見,這里我使用指針
class Node
{
public:
Node()
{
}
Node(int _x, int _y, int _z, int _val) : x(_x), y(_y), z(_z), value(_val)
{
}
int x, y, z;
int value;
friend inline std::ostream &operator<<(std::ostream &os, const Node &dt)
{
os << "[" << dt.x << ", " << dt.y << ", " << dt.z << "], [" << dt.value << "]";
return os;
}
friend bool operator==(const Node &_lhs, const Node &_rhs){
if( _lhs.x == _rhs.x &&
_lhs.y == _rhs.y &&
_lhs.z == _rhs.z ){
return true;
}
return false;
}
};
這里運算符<<
僅出於調試目的而重載
struct NodeComparator
{
bool operator()(const NodePair &_lhs, const NodePair &_rhs) const
{
if( _lhs.first == nullptr || _rhs.first == nullptr )
return false;
/*
This first check implements uniqueness.
If _lhs == _rhs --> comp(_lhs,_rhs) == false && comp(_rhs, _lhs) == false
So ( !comp(l,r) && !comp(r,l) ) == true
*/
if( *_lhs.first == *_rhs.first)
return false;
int ret = _lhs.second - _rhs.second;
return ret < 0;
}
};
我想一個問題可能是兩個節點坐標不同但 F 值相同的情況
Ì在這個例子中,我使用上面的類來插入/查找/刪除一些元素,但是它顯示在 output 上,它的行為不像預期的那樣:
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
#include <tuple>
class Node;
struct NodeComparator;
using NodePair = std::pair<Node *, int>;
using NodeSet = std::set<NodePair, NodeComparator>;
class Node
{
public:
Node()
{
}
Node(int _x, int _y, int _z, int _val) : x(_x), y(_y), z(_z), value(_val)
{
}
int x, y, z;
int value;
friend inline std::ostream &operator<<(std::ostream &os, const Node &dt)
{
os << "[" << dt.x << ", " << dt.y << ", " << dt.z << "], [" << dt.value << "]";
return os;
}
};
struct NodeComparator
{
bool operator()(const NodePair &_lhs, const NodePair &_rhs) const
{
/*
This first check implements uniqueness.
If _lhs == _rhs --> comp(_lhs,_rhs) == false && comp(_rhs, _lhs) == false
So ( !comp(l,r) && !comp(r,l) ) == true
*/
if(_lhs == _rhs)
return false;
int ret = _lhs.second - _rhs.second;
return ret < 0;
}
};
int main(int argc, char **argv)
{
Node n1(0, 2, 4, 12),
n2(2, 4, 5, 25),
n3(0, 1, 4, 34),
n4(0, 1, 4, 20),
n5(0, 1, 5, 20),
n6(0, 2, 4, 112);
NodeSet set;
set.insert({&n1, n1.value});
set.insert({&n2, n2.value});
set.insert({&n3, n3.value});
set.insert({&n4, n4.value}); //Should not be inserted because it already exists n3 with same coords
set.insert({&n5, n5.value});
//Try to insert multiple times a previously inserted node (n1 coords is == n6 coords)
//It should not be inserted because it already exists one node with the same coords (n1)
set.insert({&n6, n6.value});
set.insert({&n6, n6.value});
set.insert({&n6, n6.value});
set.insert({&n6, n6.value});
set.insert({&n6, 0});
set.insert({&n6, 1});
if (set.find({&n4, n4.value}) != set.end())
std::cout << "Found n4" << std::endl;
auto it = set.erase({&n4, 20});
std::cout << "It value (elements erased): " << it << std::endl;
if (set.find({&n4, n4.value}) != set.end())
std::cout << "Found n4 after removal" << std::endl;
std::cout << "Final Set content: " << std::endl;
for (auto &it : set)
std::cout << *it.first << std::endl;
return 0;
}
用 C++11 或以上版本編譯: g++ -o main main.cpp
Output:
Found n4
It value (elements erased): 1
Final Set content:
[0, 2, 4], [12]
[2, 4, 5], [25]
[0, 1, 4], [34]
[0, 2, 4], [112]
**預期的 Output:** 對應於元素 n1、n5、n2、n3,從 F (n1) 較小的元素 (n1) 到 F (n3) 較大的元素。
Final Set content:
[0, 2, 4], [12]
[0, 1, 5], [20]
[2, 4, 5], [25]
[0, 1, 4], [34]
我將不勝感激任何幫助或想法以及實施的替代方案。 謝謝
不幸的是,僅靠一個std::set
無法滿足您的要求。 std::set
使用相同的比較器進行排序和唯一性。 比較器沒有 state,這意味着您不能將一次與第一次進行比較,而將下一次與第二個條件進行比較。 那不管用。
因此,您需要使用 2 個容器,例如第一個使用比較器的std::unordered_set
用於相等坐標,第二個容器用於排序,例如用於排序的std::multiset
。
您還可以將std::unordered_map
與std::multiset
結合使用。
或者您將自己的容器創建為 class 並嘗試優化性能。
讓我向您展示一個使用std::set
和std::multiset
組合的示例。 它會很快,因為std::unordered_set
使用哈希。
#include <iostream>
#include <unordered_set>
#include <set>
#include <array>
#include <vector>
using Coordinate = std::array<int, 3>;
struct Node {
Coordinate coordinate{};
int value{};
bool operator == (const Node& other) const { return coordinate == other.coordinate; }
friend std::ostream& operator << (std::ostream& os, const Node& n) {
return os << "[" << n.coordinate[0] << ", " << n.coordinate[1] << ", " << n.coordinate[2] << "], [" << n.value << "]"; }
};
struct CompareOnSecond { bool operator ()(const Node& n1, const Node& n2)const { return n1.value < n2.value; } };
struct Hash {size_t operator()(const Node& n) const {return n.coordinate[0] ^ n.coordinate[1] ^ n.coordinate[2];} };
using UniqueNodes = std::unordered_set<Node, Hash>;
using Sorter = std::multiset<Node, CompareOnSecond>;
int main() {
// a vector with some test nodes
std::vector<Node> testNodes{
{ {{0, 2, 4}}, 12 },
{ {{2, 4, 5}}, 25 },
{ {{0, 1, 4}}, 34 },
{ {{0, 1, 4}}, 20 },
{ {{0, 1, 5}}, 20 },
{ {{0, 2, 4}}, 112 } };
// Here we will store the unique nodes
UniqueNodes uniqueNodes{};
for (const Node& n : testNodes) uniqueNodes.insert(n);
// And now, do the sorting
Sorter sortedNodes(uniqueNodes.begin(), uniqueNodes.end());
// Some test functions
std::cout << "\nSorted unique nodes:\n";
for (const Node& n : sortedNodes) std::cout << n << '\n';
// find a node
if (sortedNodes.find({ {{0, 1, 4}}, 20 }) != sortedNodes.end())
std::cout << "\nFound n4\n";
// Erase a node
auto it = sortedNodes.erase({ {{0, 1, 4}}, 20 });
std::cout << "It value (elements erased): " << it << '\n';
// Was it really erased?
if (sortedNodes.find({ {{0, 1, 4}}, 20 }) != sortedNodes.end())
std::cout << "\nFound n4 after removal\n";
// Show final result
std::cout << "\nFinal Set content:\n";
for (const Node& n : sortedNodes) std::cout << n << '\n';
}
最后,感謝用戶的建議和意見,我使用 Boost multi index with 2 index 實現了一個解決方案。 一個散列唯一索引和一個有序非唯一索引。 盡管如此,我還是將上面的答案標記為已接受,因為這是最標准的解決方案。
#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/key_extractors.hpp>
using namespace ::boost;
using namespace ::boost::multi_index;
struct IndexByCost {};
struct IndexByWorldPosition {};
class Node
{
public:
Node(int _val, int _i) : value(_val), index(_i) {}
int value; //NON UNIQUE
unsigned int index; //UNIQUE
friend inline std::ostream &operator<<(std::ostream &os, const Node &dt)
{
os << dt.index << ": [" << dt.value << "]";
return os;
}
};
using MagicalMultiSet = boost::multi_index_container<
Node*, // the data type stored
boost::multi_index::indexed_by< // list of indexes
boost::multi_index::hashed_unique< //hashed index wo
boost::multi_index::tag<IndexByWorldPosition>, // give that index a name
boost::multi_index::member<Node, unsigned int, &Node::index> // what will be the index's key
>,
boost::multi_index::ordered_non_unique< //ordered index over 'i1'
boost::multi_index::tag<IndexByCost>, // give that index a name
boost::multi_index::member<Node, int, &Node::value> // what will be the index's key
>
>
>;
int main(int argc, char const *argv[])
{
MagicalMultiSet container;
Node n1{24, 1};
Node n2{12, 2};
Node n3{214,3};
Node n4{224,4};
Node n5{221,5};
Node n6{221,6};
auto & indexByCost = container.get<IndexByCost>();
auto & indexByWorldPosition = container.get<IndexByWorldPosition>();
indexByCost.insert(&n1);
indexByCost.insert(&n2);
indexByCost.insert(&n3);
indexByCost.insert(&n4);
indexByCost.insert(&n5);
for(auto &it: indexByCost)
std::cout << *it << std::endl;
auto it = indexByCost.begin();
std::cout << "Best Node " << **it << std::endl;
indexByCost.erase(indexByCost.begin());
it = indexByCost.begin();
std::cout << "Best Node After erasing the first one: " << **it << std::endl;
std::cout << "What if we modify the value of the nodes?" << std::endl;
n2.value = 1;
std::cout << "Container view from index by world position" << std::endl;
for(auto &it: indexByWorldPosition)
std::cout << *it << std::endl;
auto found = indexByWorldPosition.find(2);
if(found != indexByWorldPosition.end() )
std::cout << "Okey found n2 by index" << std::endl;
found = indexByWorldPosition.find(1);
if(found != indexByWorldPosition.end() )
std::cout << "Okey found n1 by index" << std::endl;
std::cout << "Imagine we update the n1 cost" << std::endl;
n1.value = 10000;
indexByWorldPosition.erase(found);
indexByWorldPosition.insert(&n1);
std::cout << "Container view from index by cost " << std::endl;
for(auto &it: indexByCost)
std::cout << *it << std::endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.