Transforming Elements in a Sequence - C++ STL Algorithm

C++ examples for STL Algorithm:transform

Description

Transforming Elements in a Sequence

Demo Code

#include <iostream>
#include <istream>
#include <string>
#include <list>
#include <algorithm>
#include <iterator>
#include <cctype>

using namespace std;

template<typename C>
void printContainer(const C& c, char delim = ',', ostream& out = cout) {
   printRange(c.begin(), c.end(), delim, out);
}

template<typename Fwd>
void printRange(Fwd first, Fwd last, char delim = ',', ostream& out = cout) {
   out << "{";
   while (first != last) {
      out << *first;//from   ww  w .j  a v  a2 s. c o m
      if (++first != last)
         out << delim << ' ';
   }
   out << "}" << endl;
}

// Convert a string to upper case
string strToUpper(const string& s) {
   string tmp;
   for (string::const_iterator p = s.begin(); p != s.end(); ++p)
      tmp += toupper(*p);
   return(tmp);
}

string strAppend(const string& s1, const string& s2) {
   return(s1 + s2);
}

int main() {

   cout << "Enter a series of strings: ";
   istream_iterator<string> start(cin);
   istream_iterator<string> end;
   list<string> lst(start, end), out;

   transform(lst.begin(), lst.end(), back_inserter(out), strToUpper);

   printContainer(out);
   cin.clear();

   cout << "Enter another series of strings: ";
   list<string> lst2(++start, end);
   out.clear();

   transform(lst.begin(), lst.end(), lst2.begin(), back_inserter(out), strAppend);

   printContainer(out);
}

Result


Related Tutorials