back_inserter or end()

Started by
4 comments, last by adeyblue 11 years, 4 months ago
Hello,

Is there anything wrong with this:

string temp;
for(auto i = dest.begin(); i != dest.end(); ++i)
{
temp.insert(temp.end(), *i);
}
wcout << fieldTitle << "\t" << temp << endl;

I also tried:

string temp;
for(auto i = dest.begin(); i != dest.end(); ++i)
{
temp.insert(back_inserter(temp), *i);
}
wcout << fieldTitle << "\t" << temp << endl;

but it won't compile. Bjarne Stroustroup says to use back_inserters in his book, but the end() version has been working just fine for me. I was wondering if I didn't understand something.

I wonder as I wander...

http://www.davesgameoflife.com

Advertisement
Back_inserter automatically creates new elements at the back when you assign to it. Many algorithms which otherwise overwrite a range of target elements will instead insert new elements when you use back_inserter.

Your example code is a simple append operation. The cleanest way to do it would be to use the copy algorithm:
copy(begin(wherefrom), end(wherefrom), back_inserter(whereto));

BTW, your example has curious naming, you read items from "dest"...
You can't use an std::back_inserter with a string to append other strings, because std::string doesn't implement the correct interface (it only has a push_back for individual characters, not strings). If you think of a string as a container of characters, then it makes sense that you can only insert characters (since that's what the container holds).

To append strings, you should use either append() or the += operator. insert() also works, but it's a little harder to read and you have the aforementioned shortcuts to make this specific case easier to handle.
Alternative suggestion:

[source]std::wostringstream complete;
for(const std::wstring& element : container_of_strings)
complete << element;
wcout << fieldTitle << L" " << complete.str() << std::endl;[/source]


[edit] Oh, screw it. The long empty string should be an escaped t (for tab, as in the OP) but the forums keep unescaping it.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Is the code tag doing that too?

std::wostringstream complete;
for(const std::wstring& element : container_of_strings)
complete << element;
wcout << fieldTitle << L"\t" << complete.str() << std::endl;

edit: look like not. One more reason to prefer code tags over the source tags.
You could also (ab)use the fact that accumulate is implemented in terms of addition and use that to concat a bunch of strings in a container. The need to provide the starting point takes away some elegance points but it's still serviceable.


// include <numeric>
std::wcout << fieldTitle << L'\t' << std::accumulate(dest.begin(), dest.end(), std::wstring()) << std::endl;

This topic is closed to new replies.

Advertisement