c++ - Counting Occurrences In A Map -
currently writing program parse through directory (using boost library) , add file extensions, number of specific type of file, , files size map includes string , key being class. trying find total number of occurrences each file extension, total number of files found in directory , total number of bytes found in directory.
here important code:
class filestats { public: int totalfiles; long long filesize; }; map< string, filestats > filemap; filemap[diriter->path().extension()].totalfiles++; filemap[diriter->path().extension()].filesize += file_size( diriter->path()); i don't think can use .count method of maps, unless overload it, there simpler way of doing it?
unless missing something, looks have readily available. total number of extensions is
filemap.size() then can iterate of map printing number of files , byte count
for (auto i=filemap.begin(); i!=filemap.end(); ++i) cout << i->first << '=' << i->second.totalfiles << ':' << i->second.filesize << endl; here test program prints totals.
#include <iostream> #include <map> class filestats { public: int totalfiles; long long filesize; filestats() : totalfiles(0), filesize(0) {} filestats(int f, long long s) : totalfiles(f), filesize(s) {} filestats& operator+=(const filestats& other) { totalfiles += other.totalfiles; filesize += other.filesize; return *this; } }; int main(int argc, char* argv[]) { typedef std::map< std::string, filestats > map_type; map_type filemap; filemap["cpp"].totalfiles++; filemap["cpp"].filesize += 11111; filemap["h"].totalfiles++; filemap["h"].filesize += 22222; filemap["cpp"].totalfiles++; filemap["cpp"].filesize += 33333; filestats totals; (map_type::const_iterator i=filemap.begin(); i!=filemap.end(); ++i) totals += i->second; std::cout << "total files=" << totals.totalfiles << ' ' << "total size=" << totals.filesize << std::endl; return 0; }
Comments
Post a Comment