#include <iostream>
#include <iterator>
#include <algorithm>
#include <sstream>
#include <map>
/**
* Struct type to store data read from input stream.
* Provides a cast operator to convert struct data
* to a std::pair suitable for insertion into the map
*/
struct Record
{
int m_id;
std::string m_name;
Record() {}
Record(int id, const std::string& name) : m_id(id), m_name(name) {}
Record(const Record& rec) : m_id(rec.m_id), m_name(rec.m_name) {}
/**
* Cast operator
*/
operator std::pair<const int, std::string>() const { return std::make_pair(m_id, m_name); }
};
/**
* Converts a map entry to a formatted string.
*/
std::string toString(std::pair<const int, std::string> it)
{
std::stringstream tmp;
tmp << "{id: " << it->first << "; name: " << it->second << "}";
return tmp.str();
}
/**
* Overload the input operator for the Record data type
*/
std::istream& operator>>(std::istream& str, Record& rec)
{
str >> rec.m_id >> rec.m_name;
return str;
}
/**
* Main
*/
int main(void)
{
/**
* Set up the input stream. For this example, we'll use
* a string stream. The data object contains the "file"'s
* contents; a sequence of id-name pairs.
*/
std::string data = "1 foo 2 bar 3 bletch 4 blurga";
std::stringstream in;
int.str(data);
/**
* The map that we'll be loading the above data into
*/
std::map<int, std::string> vmap;
/**
* Read the entries from the input stream using an
* istream iterator and insert them into the map
*/
std::copy(std::istream_iterator<Record>(in), // initially points to the beginning of the stream
std::istream_iterator<Record>(), // indicates end of stream
std::inserter(vmap, vmap.end())); // creates an output iterator pointing to the end of the map
std::cout << "Contents of container as read from input stream: " << std::flush;
/**
* Iterate over the contents of the container and format
* them for standard output. Need to use the transform
* function since the output iterator doesn't know how to
* format std::pair types
*/
std::transform(vmap.begin(),
vmap.end(),
std::ostream_iterator<std::string>(std::cout, " "),
toString);
std::cout << std::endl;
return 0;
}