Untitled
unknown
c_cpp
4 years ago
1.9 kB
12
Indexable
#include <cmath>
#include <iostream>
#include <functional>
#include <vector>
using std::vector;
using std::function;
template <typename T, typename FunType>
vector<T> filter(const vector<T>& v, FunType p) {
vector<T> filtered;
int size = (int)v.size();
for (int i = 0; i < size; i++) {
if (p(v.at(i)) == true)
filtered.push_back(v.at(i));
}
return filtered;
}
template <typename T, typename FunType1, typename FunType2>
vector<T> transfilt(vector<T>& v, FunType1 t, FunType2 p) {
vector<T> transfiltered;
int size = (int)v.size();
for (int i = 0; i < size; i++) {
v.at(i) = t(v.at(i));
if (p(v.at(i)) == true)
transfiltered.push_back(v.at(i));
}
return transfiltered;
}
template <typename T>
void printVec(const vector<T>& v) {
int size = (int)v.size();
for (int i = 0; i < size; i++) {
if (i == 0)
std::cout << "[ ";
std::cout << v.at(i) << " ";
if (i == (size - 1))
std::cout << "] " << std::endl;
}
}
int main() {
vector<int> v{ 1, -3, 4, -2, 6, -8, 5 };
printVec(v);
vector<int> r = filter(v, [](int x) -> bool {
if (x % 2 == 0)
return true;
else return false;
});
printVec(r);
vector<int> s = filter(v, [](int x) -> bool {
if (x > 0)
return true;
else return false;
});
printVec(s);
vector<double> w{ 1.5, -3.1, 4.0, -2.0, 6.3 };
printVec(w);
double mn = -0.5, mx = 0.5;
vector<double> d =
transfilt(w, [](double x) -> double {
return std::sin(x);
}, [&](double x) -> bool {
if (x >= mn && x <= mx)
return true;
else return false;
});
printVec(w);
printVec(d);
}Editor is loading...