By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,827 Members | 2,220 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,827 IT Pros & Developers. It's quick & easy.

Another way of adding to a string (or output iterator)?

P: n/a
#include <string>
#include <vector>
#include <iostream>

class Element
{
public:
Element(std::string n) : name_(n) {};
std::string serialize() const
{
return "<element>" + name_ + "</element>";
}
private:
std::string name_;
};

int main()
{
std::vector<Element> container;
container.push_back(Element("Joe"));
container.push_back(Element("Bob"));

std::string all_serialized;

std::vector<Element>::const_iterator iter;

// Is there a cooler way of doing this loop?
// Like with std::back_inserter or std::copy or something?
// Or perhaps create Element::operator<< ?
for (iter = container.begin(); iter != container.end(); ++iter)
{
all_serialized += iter->serialize();
}

std::cout << "All elements serialized: \n" << all_serialized
<< std::endl;

return EXIT_SUCCESS;
}
Apr 10 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
In article <Ix********@news.boeing.com>,
Joe Van Dyk <jo********@boeing.com> wrote:
#include <string>
#include <vector>
#include <iostream>

class Element
{
public:
Element(std::string n) : name_(n) {};
std::string serialize() const
{
return "<element>" + name_ + "</element>";
}
private:
std::string name_;
};

int main()
{
std::vector<Element> container;
container.push_back(Element("Joe"));
container.push_back(Element("Bob"));

std::string all_serialized;

std::vector<Element>::const_iterator iter;

// Is there a cooler way of doing this loop?
// Like with std::back_inserter or std::copy or something?
// Or perhaps create Element::operator<< ?
for (iter = container.begin(); iter != container.end(); ++iter)
{
all_serialized += iter->serialize();
}

std::cout << "All elements serialized: \n" << all_serialized
<< std::endl;

return EXIT_SUCCESS;
}


ostream& operator<<( ostream& os, const Element& elem ) {
return os << elem.serialize();
}

// in main:

stringstream ss;
copy( container.begin(), container.end(),
ostream_iterator<element>( ss ) );
string all_serialized = ss.str();
Of course, you could replace the stringstream with a file stream and
*actually* serialize the elements...
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.
Apr 11 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.