Reputation: 85
I'm new to C++ and not 100% sure how I can iterate over maps.
For the project, I need to have a map that stores key: [name of file / stream] and value: [logger::severity]. Among the filenames there might be an object of ostream cout.
I came up to pretty much nothing:
enum class severity
{
trace,
debug,
information,
warning,
error,
critical
};
std::map<std::ofstream, severity> this_loggers_streams;
for (std::map<std::ofstream, severity>::iterator iter = this_loggers_streams.begin();
iter != this_loggers_streams.end(); ++iter) {
iter->first << "" << std::endl;
}
}
My IDE warns me that there is a no viable conversion for my iterator and Invalid operands to binary expression (const std::basic_ofstream<char>
and const char[1]
).
How can I iterate over my map? What will be the best solution to have an ability to write in file and in std::cout
as it can be a member of my map?
Upvotes: 1
Views: 178
Reputation: 1833
STL containers, including std::map
, can be iterated through iterators in the same way.
For example:
for(auto it{x.begin()}; it != x.end(); ++it){
// something
}
However, std::ofstream
should not be used as key_type
, since keys are constants, and therefore can not be used when a non-const context is required.
Upvotes: -2
Reputation: 38863
Keys in a map are const values. That code is invalid and can't be fixed without changing the software design:
iter->first << "" << std::endl; // iter->first is const std::ofstream
A possible change:
std::list<std::pair<std::ofstream, severity>> this_loggers_streams;
Upvotes: -1