Skip to content
No description, website, or topics provided.
C++
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.gitignore
LICENSE
README.md
demo.cpp

README.md

How simple could it be to apply a function on each element in vector?

Question

Suppose we have a function:

int square(int x) { return x * x; }

How can we apply it to a vector (or list)?

STL answer

STL provides a function transform to achieve this:

vector<int> dst(src.size());
transform(src.begin(), src.end(), dst.begin(), square);

My answer

In this repo, I constructed a function template, which could make this easier:

auto dst = square%(src);

See also

See more details in demo.cpp, and try following:

$ g++ -Wall -std=c++17 demo.cpp
$ ./a.out
vector   : 1 3 5 7 9
transform: 1 9 25 49 81
square%  : 1 9 25 49 81
list     : 1 3 5 7 9
transform: 1 9 25 49 81
square%  : 1 9 25 49 81
You can’t perform that action at this time.