#include <algorithm>
#include <chrono>
#include <iostream>
#include <set>
using Time = std::chrono::high_resolution_clock;
using ms = std::chrono::milliseconds;
template <typename T>
std::set<T> &subtract (std::set<T> &initSet, const std::set<T> &otherSet) {
auto it = initSet.cbegin();
auto end = initSet.cend();
auto otherIt = otherSet.cbegin();
auto otherEnd = otherSet.cend();
while (it != end) {
const auto &value = *it;
while (otherIt != otherEnd) {
if (*otherIt >= value) {
break;
}
++otherIt;
}
if (otherIt == otherEnd) {
break;
}
if (*otherIt == value) {
it = initSet.erase(it);
}
else {
++it;
}
}
return initSet;
}
int main()
{
std::set<int> initialSet;
auto it = initialSet.end();
for (int i = 0; i < 5000000; ++i) {
it = initialSet.emplace_hint(it, i);
}
std::set<int> diffSet;
it = diffSet.end();
for (int i = 0; i < 5000000; i += 2) {
it = diffSet.emplace_hint(it, i);
}
auto start = Time::now();
std::set<int> setSubtractedWithStl;
{
std::set<int> initialSetCopy = initialSet;
start = Time::now();
std::set_difference(initialSetCopy.cbegin(), initialSetCopy.cend(),
diffSet.cbegin(), diffSet.cend(),
std::inserter(setSubtractedWithStl, setSubtractedWithStl.end()));
}
std::cout << "Stl + destructor: " << std::chrono::duration_cast<ms>(Time::now() - start).count() << '\n';
start = Time::now();
subtract(initialSet, diffSet);
std::cout << "Heaven: " << std::chrono::duration_cast<ms>(Time::now() - start).count() << '\n';
const bool hasEqualSize = initialSet.size() == setSubtractedWithStl.size();
bool equal = false;
if (hasEqualSize) {
equal = std::equal(initialSet.cbegin(), initialSet.cend(),
setSubtractedWithStl.cbegin());
}
std::cout << "Sets are equal: " << std::boolalpha << equal << '\n';
return 0;
}