Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you perform transformation to each element and append the result in c++?

I have a set of integers {1,2}. I want to produce "Transform#1, Transform#2" where each element is tranformed and then result is accumulated with a delimiter.

What would be the easiest way to accomplish this? Do we have "folds", "maps" in c++?

We dont use boost.

like image 496
John Mcdock Avatar asked Feb 04 '19 22:02

John Mcdock


2 Answers

You can use std::transform and std::accumulate

int main()
{
  std::vector<int>         v1 {1,2,3};
  std::vector<std::string> v2;

  std::transform(begin(v1), end(v1), std::back_inserter(v2), [](auto const& i) {
    return std::string("Transform#") + std::to_string(i);
  });

  std::string s = std::accumulate(std::next(begin(v2)), end(v2), v2.at(0), [](auto const& a, auto const& b) {
    return a + ", " + b;
  });

  std::cout << s;
}

prints Transform#1, Transform#2, Transform#3

like image 101
Andreas DM Avatar answered Sep 18 '22 16:09

Andreas DM


You may want to use Range Adaptors. Boost already has them and they are coming to the standard with C++20.

Take a look at the boost::adaptors::transformed example here. Also, check out the reference to get a better picture of what operations are supported by adaptors.

In the end, you can achieve much cleaner code and the performance difference is negligible (unlike in some other languages, where using this style of programming incurs heavy performance costs).

like image 26
David Frank Avatar answered Sep 20 '22 16:09

David Frank