commit 8011db5e0ca6f3309372cebdc0a4640ace2e9c6b Author: Ramón Caballero Date: Mon Feb 8 12:25:59 2021 +0000 Demo std::reverse_copy diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..3f9762c --- /dev/null +++ b/Makefile @@ -0,0 +1,5 @@ +all: + $(CXX) reverse_copy.cpp -std=c++11 -o reverse_copy + +clean: + rm -r reverse_copy diff --git a/reverse_copy.cpp b/reverse_copy.cpp new file mode 100644 index 0000000..9e330a9 --- /dev/null +++ b/reverse_copy.cpp @@ -0,0 +1,60 @@ +#include // std::vector +#include // std::reverse_copy +#include // std::cout, std::end +#include // EXIT_SUCCESS + +// +// Quick demo of std::reverse_copy +// +// https://www.cplusplus.com/reference/algorithm/reverse_copy/ +// Copies the elements in the range [first,last) to the range beginning at result, but in reverse order. +// + +// +// We need a simple class so we can store a few of them in a vector, then we'll reverse copy onto another vector. +// + +class Batman { +public: + Batman(int batarangs); + int howManyBatarangs() const; +private: + int batarangs = 0; +}; + +Batman::Batman(int batarangs): batarangs(batarangs) { +} + +int Batman::howManyBatarangs() const { + return this->batarangs; +} + +// + +int main(int argc, char **argv) { + + // Create some pointers to the simple class: + Batman* b0 = new Batman(0); + Batman* b1 = new Batman(1); + Batman* b2 = new Batman(2); + Batman* b3 = new Batman(3); + + // Store those pointers in a vector: + std::vector a = { b0, b1, b2, b3 }; + + // Way 1: if for some reason the destination vector is already created and we don't have access (or don't want) to modify its declaration... + std::vector b; + b.resize(a.size()); // ...then we need to resize it to the same size of the original vector. + + // Way 2: if we can create the destination vector... + // std::vector b(a.size()); // ...we can just create it with the same size of the original vector. + + // + std::reverse_copy(a.begin(), a.end(), b.begin()); + + // Output the elements of each vector: + for (auto x: a) std::cout << x->howManyBatarangs() << std::endl; + for (auto x: b) std::cout << x->howManyBatarangs() << std::endl; + + return EXIT_SUCCESS; +}