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

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top