Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a std::back_insert_iterator be used on a std::ostream?

As per the title question.

I assume that the answer is "No, because the std::back_insert_iterator object calls push_back() on the container."

If the answer is in fact no, then is there any template class iterator that I can use in my template function to both append to a std::string, append to a std::vector<char>, and write to an std::ostream?

like image 396
magnus Avatar asked Aug 21 '26 05:08

magnus


1 Answers

This is what std::ostream_iterator is for:

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

int main()
{
    char c[] = { 'a', 'b', 'c', 'd' };

    std::vector<char> v;
    std::string s;

    std::copy(c, c+4, std::back_inserter(v));
    std::copy(c, c+4, std::back_inserter(s));
    std::copy(c, c+4, std::ostream_iterator<char>(std::cout));
}

DEMO

like image 143
Piotr Skotnicki Avatar answered Aug 23 '26 19:08

Piotr Skotnicki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!