Last active
March 27, 2022 08:08
-
-
Save JaHIY/0c3810bcdfe6f7884285680d16a83e33 to your computer and use it in GitHub Desktop.
uniq array in-place
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using std::cout; | |
using std::endl; | |
#include <vector> | |
using std::vector; | |
#include <algorithm> | |
using std::swap; | |
#include <concepts> | |
using std::is_swappable_v; | |
using std::equality_comparable; | |
template<typename T> | |
requires equality_comparable<T> && is_swappable_v<T> | |
typename vector<T>::size_type uniq_array(vector<T>& array) { | |
typename vector<T>::size_type k = array.size() - 1; | |
typename vector<T>::size_type j = 0; | |
for (; j <= k; j += 1) { | |
for (typename vector<T>::size_type i = j + 1; i <= k; i += 1) { | |
if (array[j] == array[i]) { | |
while (array[j] == array[k] && i <= k) { | |
k -= 1; | |
} | |
if (i <= k) { | |
if (i != k) { | |
swap(array[i], array[k]); | |
} | |
k -= 1; | |
} | |
} | |
} | |
} | |
return j; | |
} | |
int main(void) { | |
vector<int> a{1,1,1,2,2,1,1,1}; | |
vector<int>::size_type array_size = uniq_array(a); | |
for (vector<int>::size_type i = 0; i < array_size; i += 1) { | |
cout << a[i] << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment