We are here to help.
I analysed the code and checked, what could be the issue here.
From this, you can derive measures for improvements.
Please check the below list, maybe this gives you and idea for further development.
You pass the input vector by reference, but then copy all the data. No need to do. Use the given input vector as is. Except, of course, if the source data is still neded
You define your resulting std::vector
"pairs" but do not reserve memory for this. Using push_back
on this std::vector
will do a lot of memory reallocation and copying. Please use std::pairs.reserve(vec.size()/2);
after the definition of "pairs".
No need to handover "greater" to the sort function. The sort function will do that by default
Double nested loops are not needed. Your values are already sorted. You can use a single loop and then compare vec[i] with [vec[i+1]. This will reduce the complexity from quadratic to linear.
At the end, you sort again the pairs. This is not necessary, as the values were already sorted before
Please compile with all optimizations on, like "Release Mode" or "-O3"
See the below example which creates fist 10.000.000 random and unique test values and then measures the execution of the operation for finding the required pairs.
Execution time is below 1 second on my machine.
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <random>
#include <unordered_set>
#include <limits>
#include <chrono>
#include <fstream>
constexpr size_t MaxValues = 10'000'000;
std::vector<int> createTestValues() {
std::random_device rd; // Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> distrib(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
std::unordered_set<int> values{};
while (values.size() < MaxValues)
values.insert(distrib(gen));
return { values.begin(), values.end() };
}
int main() {
std::vector values = createTestValues();
auto start = std::chrono::system_clock::now();
// Main algorithm ------------------------------------------
std::vector<std::pair<int, int>> result;
result.reserve(values.size() / 2);
std::sort(values.begin(), values.end());
for (size_t k{}; k < values.size() - 1; ++k)
if (values[k + 1] - values[k] == 2)
result.push_back({ values[k] , values[k + 1] });
// ------------------------------------------------------
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);
std::cout << "Elapsed time: " << elapsed.count() << " ms\n\n";
std::ofstream ofs{ "test.txt" };
for (const auto& [v1, v2] : result) ofs << v1 << '\t' << v2 << '\n';
}