您始终可以将std::tie
每个数据成员放入一个std::tuple
并使用字典排序来对指向您的大数据结构的指针向量进行排序。然后,您可以std::unique
在复制输出之前对该数据结构进行操作。通过一个小的修改,您还可以通过直接对大Item
向量进行排序来删除重复的内容。
#include <tuple>
#include <memory>
#include <vector>
// tuples have builtin lexicographic ordering,
// I'm assuming all your Item's data members also have operator<
bool operator<(Item const& lhs, Item const& rhs)
{
return std::tie(lhs.first_data, /*...*/ lhs.last_data) < std::tie(rhs.first_data, /*...*/ rhs.last_Data);
}
int main()
{
// In the Beginning, there was some data
std::vector<Item> vec;
// fill it
// init helper vector with addresses of vec, complexity O(N)
std::vector<Item*> pvec;
pvec.reserve(vec.size());
std::transform(std::begin(vec), std::end(vec), std::back_inserter(pvec), std::addressof<Item>);
// sort to put duplicates in adjecent positions, complexity O(N log N)
std::sort(std::begin(pvec), std::end(pvec), [](Item const* lhs, Item const* rhs){
return *lhs < *rhs; // delegates to operator< for Item
});
// remove duplicates, complexity O(N)
auto it = std::unique(std::begin(pvec), std::end(pvec), [](Item const* lhs, Item const* rhs){
return *lhs == *rhs; // assumes Item has operator==, if not use std::tuple::operator==
});
pvec.erase(it, std::end(pvec));
// copy result, complexity O(N)
std::vector<Item> result;
result.reserve(pvec.size());
std::transform(std::begin(pvec), std::end(pvec), std::back_inserter(result), [](Item const* pelem){
return *pelem;
});
// And it was good, and done in O(N log N) complexity
}