Sign in to follow this  
pulpfist

Printing a sequence to cout. Problem with trailing output

Recommended Posts

Hiyas I'm printing a sequence of map keys to cout using
template<class K, class V> 
string pairToString(const pair<K, V*>& p) { return p.first; }
...
transform(location.units.begin(), location.units.end(), 
	ostream_iterator<string>(out, ", "), pairToString<string, Unit>);
and I'm getting an extra ", " at the end of the output. How do I get rid of that in a slick way?

Share this post


Link to post
Share on other sites
Hmm this is the closest I can get...

template<class K, class V>
struct stringAppender
{
stringAppender(std::string& s) : m_str(&s) {}

void operator()(const std::pair<K, V*>& p) const
{
static bool mFirst = true;
*m_str += (mFirst ? "" : ", ") + p.first;
mFirst = false;
}

std::string* m_str;
};
...
string s = "Available actions: ";
std::copy(unit.actions.begin(), unit.actions.end(),
boost::make_function_output_iterator(stringAppender<string, Action>(s)));

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this