Add td::unique helper method.

This commit is contained in:
levlam 2020-12-30 18:12:43 +03:00
parent 371ec422e6
commit 18be33a18c
2 changed files with 40 additions and 0 deletions

View File

@ -124,6 +124,26 @@ bool remove(V &v, const T &value) {
return true;
}
template <class V>
void unique(V &v) {
if (v.empty()) {
return;
}
std::sort(v.begin(), v.end()); // caller will need to #include <algorithm>
size_t j = 1;
for (size_t i = 1; i < v.size(); i++) {
if (v[i] != v[i - 1]) {
if (i != j) {
v[j] = std::move(v[i]);
}
j++;
}
}
v.resize(j);
}
template <class V, class T>
bool contains(const V &v, const T &value) {
for (auto &x : v) {

View File

@ -38,6 +38,7 @@
#include "td/utils/unicode.h"
#include "td/utils/utf8.h"
#include <algorithm>
#include <atomic>
#include <clocale>
#include <limits>
@ -346,6 +347,25 @@ TEST(Misc, remove) {
test_remove(v, 1, v);
}
static void test_unique(td::vector<int> v, td::vector<int> expected) {
td::unique(v);
ASSERT_EQ(expected, v);
}
TEST(Misc, unique) {
test_unique({1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6});
test_unique({5, 2, 1, 6, 3, 4}, {1, 2, 3, 4, 5, 6});
test_unique({}, {});
test_unique({0}, {0});
test_unique({0, 0}, {0});
test_unique({0, 1}, {0, 1});
test_unique({1, 0}, {0, 1});
test_unique({1, 1}, {1});
test_unique({3, 3, 3, 3, 3, 2, 2, 2, 1, 1, 0}, {0, 1, 2, 3});
test_unique({3, 3, 3, 3, 3}, {3});
test_unique({3, 3, -1, 3, 3}, {-1, 3});
}
TEST(Misc, contains) {
td::vector<int> v{1, 3, 5, 7, 4, 2};
for (int i = -10; i < 20; i++) {