Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

looking for an std algorithm to replace a simple for-loop

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading