cppcourse/src/sheet06.cpp
2022-12-17 21:35:56 +01:00

94 lines
2.1 KiB
C++

#include<iostream>
#include<exception>
#include<math.h>
#include <string>
#include <tuple>
#include<vector>
#include<algorithm>
#include<functional>
#define MY_ASSERT(BOOL_EXPR, MESSAGE) { \
if (!BOOL_EXPR) \
{ \
std::cout << MESSAGE << '\n'; \
std::cout << "File: " << __FILE__ << '\n'; \
std::cout << "Line: " << __LINE__ << '\n'; \
std::terminate(); \
} \
}
#define POWER(RESULT, BASE, EXPONENT) \
{ \
RESULT = std::pow(BASE,EXPONENT); \
}
template<typename A, typename B, typename C>
struct Triple
{
A first;
B second;
C third;
Triple(A a, B b, C c) : first(a), second(b), third(c) {}
friend std::ostream& operator<< (std::ostream& os, const Triple& t)
{
os << '(' << t.first <<", " << t.second << ", " << t.third << ')';
return os;
}
};
template<typename T>
void bubble_sort(std::vector<T> &v, std::function<bool(T,T)> predicate)
{
bool has_swapped;
size_t n = v.size();
do
{
has_swapped = false;
for(size_t i=0; i < n-1; ++i)
{
if(predicate(v[i],v[i+1]))
{
std::swap(v[i], v[i+1]);
has_swapped = true;
}
}
--n;
}while(has_swapped);
}
template<typename A>
A add(A a)
{
return a;
}
template<typename A, typename... Args>
A add(A a, Args... args)
{
return a + add(args...);
}
int main()
{
MY_ASSERT(true, "hey :)");
int i;
POWER(i, 2, 3);
std::cout << i << '\n';
Triple<int, int, int> t(1,2,3);
std::cout << t << '\n';
std::vector<double> v = {10.0,9.0,8.0,7.0,6.0,5.0,4.0,1.0,3.0,2.0,1.1,1.2,1.1};
std::for_each(v.begin(), v.end(), [](double i) { std::cout << i << '\t';});
std::cout << '\n';
bubble_sort<double>(v, [](const double a, const double b){return a>b;});
std::for_each(v.begin(), v.end(), [](double i) { std::cout << i << '\t';});
std::cout << '\n';
int isum = add(1,2,3,4,5,6,7,8,9,10);
std::cout << isum << '\n';
std::string s1 = "Hello";
std::string s2 = ", ";
std::string s3 = "World";
std::string s4 = "!";
std::string ssum = add(s1,s2,s3,s4);
std::cout << ssum << '\n';
return 0;
}