School notes / Charles University / Advanced C++
Czech notesLecture 13
Download Markdown · Download PDF
Prasarny s Bednarkem:
pokud mam 3 vnorene cykly co indexuji do 2D poli, tak nevim, jestli to ma byt b[k][j] nebo b[j][k] - pak to nefunguje
Jak odhalit, ze tam takovou chybu mame?
Abychom nedelali of by one error - ze dame <= misto < muzeme udelat pomoci iterovani prez iota:
auto L = std::views::iota(0, l);
auto M = std::views::iota(0, m);
auto N = std::views::iota(0, n);
for (auto i : L) {
for (auto j : M) {
for (auto k : N) {
b[j][k] = a[i][j] * c[k][i];
}
}
}
abych mohl rozlisovat mezi jednotlivymi dimenzemi, tak muzu pouzit ruzne typy pro indexovani - to se standardne dela pomoci tagovych struktur
struct dimension_tag_base {}; // to je portreba, abychom nemohli pouzit stejny tag pro i jine veci / nedali float jako tag
struct dim_i : dimension_tag_base {};
struct dim_j : dimension_tag_base {};
struct dim_k : dimension_tag_base {};
template<typename Dim>
struct tagged_range {
int begin, end;
int current;
auto begin() const { return begin; }
auto end() const { return end; }
template<typename Dim>
struct tagged_iterator {
int value;
// implementace iteratoru
}
tagged_iterator<Dim> operator*() const { return {current}; }
};
constexpr auto L = tagged_range<dim_i>(0, l);
constexpr auto M = tagged_range<dim_j>(0, m);
constexpr auto N = tagged_range<dim_k>(0, n);
dimension_tag_base je dulezite protoze:
jinak bychom si mohli udelat nejaky range, ktery by mel float jako tag a iteroval by prez tagy
=== muzu si undelat tezor<> misto matice ktery bude kontrolovat typy indexu a dimenzi navic pak muzu udelat owerload na [] abychom mohli prohazovat indexy v dimenzich
===
mame se naucit jak pouzivat templatove veci a jaky je rozdim mezi & && * atp.
===
Corutiny
Pr: Fibonacci:
std::generator<int> fib(){
int a = 0;
int b = 1;
while(true){
auto old_b = b;
b = a + b;
a = old_b;
co_yield a;
}
}
int main() {
std::print("{} ", fib());
}