record_writer.h
Go to the documentation of this file.
00001 #ifndef BWI_TOOLS_RECORD_WRITER_H
00002 #define BWI_TOOLS_RECORD_WRITER_H
00003 
00004 #include <fstream>
00005 #include <map>
00006 #include <string>
00007 #include <vector>
00008 
00009 #include <boost/algorithm/string/join.hpp>
00010 #include <boost/foreach.hpp>
00011 #include <boost/range/adaptor/map.hpp>
00012 #include <boost/range/algorithm/copy.hpp>
00013 
00014 namespace bwi_tools {
00015   
00016   inline bool writeRecordsAsCSV(const std::string &filename,
00017                                 const std::vector<std::map<std::string, std::string> > &records) {
00018 
00019     // Get the superset of keys for all records.
00020     std::set<std::string> all_keys;
00021     typedef std::map<std::string, std::string> StringMap;
00022     BOOST_FOREACH(const StringMap& record, records) {
00023       // TODO std::inserter may be an inefficient way of copying the keys to the all_keys set
00024       boost::copy(record | boost::adaptors::map_keys, std::inserter(all_keys, all_keys.begin()));
00025     }
00026 
00027     // Create the file and write the header
00028     std::ofstream ofs(filename.c_str());
00029     if (!ofs.is_open()) {
00030       return false;
00031     }
00032     ofs << boost::algorithm::join(all_keys, ",") << std::endl;
00033 
00034     // Go through each record, check if a key is there, otherwise insert a 0.
00035     BOOST_FOREACH(const StringMap& record, records) {
00036       std::vector<std::string> vals;
00037       BOOST_FOREACH(const std::string& key, all_keys) {
00038         StringMap::const_iterator value_iter = record.find(key); 
00039         if (value_iter == record.end()) {
00040           vals.push_back("0");
00041         } else {
00042           vals.push_back(value_iter->second);
00043         }
00044       }
00045       ofs << boost::algorithm::join(vals, ",") << std::endl;
00046     }
00047 
00048     ofs.close();
00049   }
00050 
00051 } /* bwi_tools */
00052 
00053 #endif /* end of include guard: BWI_TOOLS_RECORD_WRITER_H */


bwi_tools
Author(s): Piyush Khandelwal
autogenerated on Fri Aug 28 2015 10:14:30