jeudi 18 novembre 2021

std::map with Filename as key and Filedescriptor as Value

I am iterating through a vector, and each entry in the vector has to be written to a file depending on the entry.

Let's say Vector {File A, File B, File C, File A....}

So, multiple file descriptors are open and I am storing them in a std::map:

Key = Filename and Value = FileDescriptor. See code below.

When a Filename is not found in the map, I insert into the map a pair of data (filename, filedescriptor). The compiler is throwing an error. See error details below after the code.

std::map <std::string, std::ofstream> filemap; // maintains filename for each item in the list.

std::vector <std::string> items;

for (i=0 ; i < items.size() ; i++) {

  if (keyfilemap.find(items[i]) == keyfilemap.end()) {
      std::ofstream ofs (items(i), std::ofstream::out);
      ofs << key.first << "-" << key.second << std::endl;
      // **Compiler throws an error here.**
      keyfilemap.insert(std::make_pair(filename, ofs));
        
  }
  else 
     keyfilemap[filename] << key.first << "-" << key.second << std::endl;
}

Compiler Error.

/usr/include/c++/7/bits/stl_pair.h:529:14: error: no matching function for call to 'std::pair<std::__cxx11::basic_string<char>, std::basic_ofstream<char> >::pair(std::__cxx11::basic_string<char>&, std::basic_ofstream<char>&)'
       return __pair_type(std::forward<_T1>(__x), std::forward<_T2>(__y));

Aucun commentaire:

Enregistrer un commentaire