Delete
Delete

Reputation: 299

Counting Occurrences In A Map

Currently writing a program that will parse through a directory (using the boost library) and add file extensions, the number of that specific type of file, and the files size to a map that includes a string and the key being a class. I am now trying to find the total number of occurrences for each file extension, the total number of files that were found in the directory and the total number of bytes found in the directory.

Here is the 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 I can use the .count method of maps, unless I overload it, but is there another simpler way of doing it?

Upvotes: 2

Views: 919

Answers (1)

skuzniar
skuzniar

Reputation: 121

Unless I am missing something, looks like you have everything readily available. Total number of extensions is

fileMap.size()

Then you can iterate of this map printing number of files and byte count

for (auto i=fileMap.begin(); i!=fileMap.end(); ++i)
    cout << i->first << '=' << i->second.totalFiles << ':' << i->second.fileSize << endl;

Here is the test program that 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;
  for (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;

}

Upvotes: 2

Related Questions