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

J

Joe Van Dyk

#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::eek:perator<< ?
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;
}
 
D

Daniel T.

Joe Van Dyk said:
#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::eek:perator<< ?
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...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,189
Members
46,735
Latest member
HikmatRamazanov

Latest Threads

Top