Last active
November 23, 2023 21:24
-
-
Save DusteDdk/fa1a70af92c6712bdc7b09fed976d55c to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
A class Keeper keeps a collection of numbers | |
The collection can be replaced by calling the update method with new numbers. | |
The method ends by detailing the changes made to the collection. (what remained the same, what was added, what was removed). | |
Output: | |
$ g++ --std=c++2a -fconcepts main.cpp && ./a.out | |
New: 1 2 3 4.2 0 | |
Remaining: | |
Deleted: | |
Current: 0 1 2 3 4.2 | |
New: 8 10 | |
Remaining: 0 4.2 | |
Deleted: 1 2 3 | |
Current: 0 4.2 8 10 | |
*/ | |
#include <iostream> | |
#include <set> | |
#include <vector> | |
template <typename T> class Keeper { | |
private: | |
std::set<T> numbers; | |
public: | |
void update(std::vector<T> nums) { | |
std::set<T> nextNumbers; | |
std::vector<T> added, remaining, removed; | |
for(auto n : nums) | |
{ | |
if(numbers.contains(n)) { | |
remaining.push_back(n); | |
nextNumbers.insert(n); | |
numbers.erase(n); | |
} else { | |
added.push_back(n); | |
nextNumbers.insert(n); | |
} | |
} | |
for(auto n: numbers) { | |
removed.push_back(n); | |
} | |
numbers = nextNumbers; | |
showIterable(added, "New: "); | |
showIterable(remaining, "Remaining: "); | |
showIterable(removed, "Deleted: "); | |
showIterable(numbers, "Current: "); | |
} | |
void showIterable( auto v, std::string str) { | |
std::cout << str; | |
for(auto n: v) { | |
std::cout << n << " "; | |
} | |
std::cout << std::endl; | |
} | |
}; | |
int main() { | |
Keeper<float> k; | |
std::cout << std::endl; | |
k.update( {1, 2, 3, 4.2, 0}); | |
std::cout << std::endl; | |
k.update( {0,4.2,8,10}); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment