Skip to content

Instantly share code, notes, and snippets.

@DeveloperPaul123
Created April 8, 2018 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeveloperPaul123/344aa61aa4601d15884bb9534cc2a6d0 to your computer and use it in GitHub Desktop.
Save DeveloperPaul123/344aa61aa4601d15884bb9534cc2a6d0 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>
#include <unordered_map>
template<typename InputIterator, typename T, typename Functor>
void split(InputIterator first, InputIterator last, const T& t, Functor f)
{
while(true)
{
InputIterator found = std::find(first, last, t);
f(first, found);
if(found == last)
{
break;
}
first = ++found;
}
}
template<typename Container, typename T = typename Container::value_type>
Container find_unique(const Container &container)
{
std::unordered_map<T, int> histogram;
Container output;
for(const auto &value: container)
{
++histogram[value];
}
std::copy_if(container.begin(), container.end(), std::back_inserter(output), [&](const auto& value) -> bool
{
return histogram[value] == 1;
});
return output;
}
template<typename Container, typename Functor>
Container keep_if(const Container &container, Functor f)
{
Container output;
std::copy_if(container.begin(), container.end(), std::back_inserter(output), f);
return output;
}
int main()
{
std::vector<int> values {1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 9, 9, 10, 10, 11, 14, 16};
auto uniques = find_unique(values);
std::cout << "Found " << uniques.size() << " unique items." << std::endl;
for(auto item: uniques)
{
std::cout << "Found unique item: " << item << std::endl;
}
std::string test("hello,split,by,string");
split(test.begin(), test.end(), ',', [](std::basic_string<char>::iterator begin, std::basic_string<char>::iterator end)
{
std::string output(begin, end);
std::cout << output << std::endl;
});
auto ones = keep_if(values, [](int value) { return value == 1;});
std::cout << "There are " << ones.size() << " ones" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment