Demo std::reverse_copy
This commit is contained in:
5
Makefile
Normal file
5
Makefile
Normal file
@@ -0,0 +1,5 @@
|
||||
all:
|
||||
$(CXX) reverse_copy.cpp -std=c++11 -o reverse_copy
|
||||
|
||||
clean:
|
||||
rm -r reverse_copy
|
||||
60
reverse_copy.cpp
Normal file
60
reverse_copy.cpp
Normal file
@@ -0,0 +1,60 @@
|
||||
#include <vector> // std::vector
|
||||
#include <algorithm> // std::reverse_copy
|
||||
#include <iostream> // std::cout, std::end
|
||||
#include <cstdlib> // 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<Batman*> 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<Batman*> 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<Batman*> 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;
|
||||
}
|
||||
Reference in New Issue
Block a user