boost::adaptors::replaced

References

Headers

boost::adaptors::replaced is available by including any of the following headers:

  • boost/range/adaptor/replaced.hpp or
  • boost/range/adaptors.hpp

Examples

replaced-pipe.cpp

#include <iostream>
#include <vector>

#include <boost/range/adaptors.hpp>

const std::string str = "Boboo";


bool is_b_ignorecase(char c) {
    return c == 'b' || c == 'B';
}

int main() {
    // replaced() is a straight-forward, element-wise replace operation.
    // All elements equal to 'o' are replaced with 'a'.
    // To get dynamic control over the replacement string, use transformed().
    std::cout << "Replace 'o' in \"" << str << "\": "
              << (str | boost::adaptors::replaced('o', 'a'))
              << std::endl;

    // replaced_if() still has a constant replacement value, but whether a
    // substitution should be performed is determined by a predicate.
    std::cout << "Replace upper and lower case 'b's in \"" << str << "\": "
              << (str | boost::adaptors::replaced_if(is_b_ignorecase, 'j'))
              << std::endl;

    return 0;
}

Output:

Replace 'o' in "Boboo": Babaa
Replace upper and lower case 'b's in "Boboo": jojoo

 

istream_range.cpp

#include <iostream>
#include <sstream>

#include <boost/range/adaptors.hpp>
#include <boost/range/istream_range.hpp>


int main() {
    // istream_range() turns an input iterator into a range object.
    // The template argument type defines the type read from the stream.
    // See std::istream_iterator for more information.
    std::istringstream ss("The quick brown fox jumps over the lazy dog.");
    auto input_range = boost::istream_range<std::string>(ss);
    for (const auto &input : input_range | boost::adaptors::strided(2)) {
        std::cout << "[" << input << "] ";
    }
    std::cout << std::endl;

    std::istringstream ss2("8 2");
    auto input_range2 = boost::istream_range<int>(ss2);
    for (int input : input_range2 | boost::adaptors::replaced(8, 4)) {
        std::cout << input;
    }
    std::cout << std::endl;

    return 0;
}

Output:

[The] [brown] [jumps] [the] [dog.] 
42

 

Boost Range for Humans

This reference is part of Boost Range for Humans. Click the link to the overview.