英文:
Iterating through custom map && handling several streams
问题
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.
我是C++的新手,不太确定如何遍历映射。在这个项目中,我需要一个映射,它将键:[文件名/流的名称] 和 值:[logger::severity] 存储在其中。在文件名中可能会有一个 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]
).
我的集成开发环境警告我,我的迭代器没有合适的转换,以及二进制表达式的操作数无效(const std::basic_ofstream<char>
和 const char[1]
)。
How can I iterate over my map? What will be the best solution to have an ability to write in a file and in std::cout
as it can be a member of my map?
我该如何遍历我的映射?如何最好地实现在文件和std::cout
中写入数据,因为它可能是我的映射的成员之一?
英文:
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?
答案1
得分: -1
地图中的键是常量值。那段代码是无效的,如果不改变软件设计,就无法修复:
iter->first << "" << std::endl; // iter->first 是 const std::ofstream
一个可能的更改:
std::list<std::pair<std::ofstream, severity>> this_loggers_streams;
英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论