Home > Enterprise >  looking for an std algorithm to replace a simple for-loop
looking for an std algorithm to replace a simple for-loop

Time:04-08

Is there a standard algorithm in the library that does the job of the following for-loop?

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>


int main( )
{
    const char oldFillCharacter { '-' };
    std::vector<char> vec( 10, oldFillCharacter ); // construct with 10 chars
    // modify some of the elements
    vec[1] = 'e';
    vec[7] = 'x';
    vec[9] = '{';

    const char newFillCharacter { '#' };

    for ( auto& elem : vec ) // change the fill character of the container
    {
        if ( elem == oldFillCharacter )
        {
            elem = newFillCharacter;
        }
    }

    // output to stdout
    std::copy( std::begin( vec ), std::end( vec ),
               std::ostream_iterator<char>( std::cout, " " ) );
    std::cout << '\n';
    /* prints: # e # # # # # x # { */
}

I want to replace the above range-based for-loop with a one-liner if possible. Is there any function that does this? I looked at std::for_each but I guess it's not suitable for such a scenario.

CodePudding user response:

This loop will replace every occurrence of oldFillCharacter with newFillCharacter. If you don't want to do something more fancy std::replace looks good:

std::replace(std::begin(vec), std::end(vec), oldFillCharacter, newFillCharacter);

Or a bit simpler with std::ranges::replace:

std::ranges::replace(vec, oldFillCharacter, newFillCharacter);

CodePudding user response:

You can use std::for_each.

std::for_each(vec.begin(), vec.end(), [](char& elem) { 
    if ( elem == oldFillCharacter ) elem = newFillCharacter;
    });

CodePudding user response:

std::replace(vec.begin(), vec.end(), '_', '#');
  • Related