Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tag dispatching, Erase-remove idiom & Mutable lambdas
#include <algorithm>
#include <iostream>
#include <vector>
struct T {
~T() {
std::cout << "destroy" << std::endl;
}
};
int main() {
std::vector<int> v = {0,3,1,5,6,5,5,4,7,9};
v.erase(std::remove(v.begin(), v.end(), 5), v.end());
int n = 5;
int a[n] = {0, 1, 2, 3, 4};
n = std::remove(a, a + n, 3) - a;
std::sort(v.begin(), v.end());
v.erase(std::unique(v.begin(), v.end()), v.end());
std::vector<T> u(5);
u.resize(3);
std::cout << std::endl;
return 0;
}
#include <iostream>
#include <vector>
#include <functional>
#include <string>
std::vector<std::function<std::string()>> v;
void add(const std::string& s) {
v.push_back([name = s + "!"]() {
return name;
});
}
struct F {
int y;
F(int y_) {
y = y_;
}
int operator()(int x) {
y++;
return x + y;
}
};
int main() {
int y = 0, z = 0;
auto f = [y](int x) mutable {
y++;
return x + y;
};
f(1);
f(1);
std::cout << f(1) << std::endl;
std::cout << y << std::endl;
{
std::string au = "au";
std::string hse = "hse";
add(au);
add(hse);
}
for (auto f : v)
std::cout << f() << std::endl;
return 0;
}
#include <iostream>
#include <list>
#include <vector>
struct forward_iterator_tag {};
struct random_access_iterator_tag {};
template<class It>
struct iterator_traits {};
template<>
struct iterator_traits<std::vector<int>::iterator> {
typedef random_access_iterator_tag iterator_category;
};
template<>
struct iterator_traits<std::list<int>::iterator> {
typedef forward_iterator_tag iterator_category;
};
namespace impl {
template<class It>
It advance(It iterator, int n, forward_iterator_tag) {
std::cout << "O(n)" << std::endl;
for (int i = 0; i < n; i++) {
iterator++;
}
return iterator;
}
template<class It>
It advance(It iterator, int n, random_access_iterator_tag) {
std::cout << "O(1)" << std::endl;
return iterator + n;
}
}
template<class It>
It advance(It iterator, int n) {
return impl::advance(iterator, n, typename iterator_traits<It>::iterator_category());
}
int main() {
std::vector<int> v;
std::list<int> l;
for (int i = 0; i < 5; i++) {
v.emplace_back(i);
l.emplace_back(i);
}
std::cout << *advance(v.begin(), 3) << std::endl;
std::cout << *advance(l.begin(), 4) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.