C++ STL Alternatives to Non-STL Code

February 24, 2014

Below is a collection of examples of common code patterns that could otherwise be written simpler, cleaner, and more correct when the STL or boost is used.

Call a Function with Each Value in a Sequence

for (size_t x = 0; x < v.size(); x++)
{
    func(v[x]);
}
std::for_each(v.begin(), v.end(), func);

Get the Sum of a Sequence

long long z = 0;
for (size_t x = 0; x < v.size(); x++)
{
    z += v[x];
}
long long z = std::accumulate(v.begin(), v.end(), 0LL);

Be careful with std::accumulate.

Get the Product of a Sequence

long long z = 1;
for (size_t x = 0; x < v.size(); x++)
{
    z *= v[x];
}
long long z = std::accumulate(v.begin(), v.end(), 1, std::multiplies<long long>());

Write the Values of a Sequence to a Stream

std::ostringstream ss;
for(size_t x = 0; x < v.size(); x++)
{
    ss << v[x] << "\n";
}
std::ostringstream ss;
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(ss,"\n"));

Read the Contents of a File Into a String

std::string data;
std::ifstream in(filename.c_str());
do
{
   char ch = in.get();
   if (in)
   {
      data.push_back(ch);
   }
} while(in);
std::string data;
std::ifstream in(filename.c_str());
std::copy(std::istreambuf_iterator<char>(in), 
          std::istreambuf_iterator<char>(), 
          std::back_inserter(data));

Reverse a Sequence

for (size_t i = 0; i < v.size()/2; i++)
{ 
   std::swap(v[v.size()-i-1],v[i]);
}
std::reverse(v.begin(),v.end());

Fill a Sequence With Generated Values

int RandomNumber () { return (std::rand()%100); }
 
std::srand(unsigned(std::time(0)));
std::vector<int> v;
for (size_t x = 0; x < 10;x++)
{
   v.push_back(RandomNumber());
}
std::vector<int> v(10);
std::generate(v.begin(), v.end(), RandomNumber);

Related Posts

8 Comments

Comment February 25, 2014 by anonymous
>long long x = 0; >for (size_t x = 0; Marvelous scoping
Comment February 25, 2014 by digitalpeer
Thanks and fixed.
Comment February 25, 2014 by anonymous
For the product of a sequence non STL you need to initialize z to 1 not 0
Comment February 25, 2014 by digitalpeer
Thanks and fixed.
Comment February 25, 2014 by José Díez
Shouldn't "Get the product of a sequence" have an initialiser value of 1LL?
Comment February 28, 2014 by Ax2
Who nowadays use non-Unicode strings??
Comment March 2, 2014 by digitalpeer
While not related to this post, the previous comment about Unicode got its own post: http://www.digitalpeer.com/blog/php-and-unicode
Comment March 16, 2014 by Ryan Dougherty
You may want to avoid std::rand in the section "Fill a Sequence With Generated Values" because it (possibly) generates non-uniform random values. See this: channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful