C++ std::transform with std::vector














































C++ std::transform with std::vector



 This article is about the transform() algorithm function with std::vector container. It is
 an STL algorithm in <algorithm> header file. It applies an operation to each of the elements
 of one or two ranges and stores the result in the result vector.

 transform() can take two forms:
(1)unary operation - template <class InputIterator, class OutputIterator,
                                 class UnaryOperation>
OutputIterator transform (InputIterator first1, InputIterator last1,
OutputIterator result, UnaryOperation op);
(2)binary operation - template <class InputIterator1, class InputIterator2,
                                 class OutputIterator, class BinaryOperation>
OutputIterator transform (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
BinaryOperation binary_op);
Unary operation applies op to each of the elements in the range [first, last) and stores the
 value in the result range.
 Binary operation applies the binary_op to each of the elements of the first range along with
 the respective element of the second range. Then the value is stored in the result.

 The input range and output range can be same as well.

Return value: An iterator is returned which points to the last element written in the result
               sequence.

Here the first definition is discussed.

 Program:
 CBSE has decided to award grace marks to the students whose marks in mathematics is less
 than 90. Input the marks and accordinly award grace marks if applicable.

#include<iostream>
#include<algorithm> // for transform
#include<vector>

using namespace std;
// grace function
int grace(int a)
{
if(a<90)
return a+5;
return a;
}

int main()
{
int n,i,m;
cout<<"Enter the number of students whose marks is to be entered: ";
cin>>n;

vector<int> marks;
cout<<"Enter the marks of the students: ";
for(i=0;i<n;i++)
{
cin>>m;
marks.push_back(m);
}
transform(marks.begin(),marks.end(),marks.begin(),grace);

cout<<"Updated marks of the students: "<<endl;
for(auto it=marks.begin();it!=marks.end();it++)
cout<<*it<<endl;
return 0;
}

Comments