gpt4 book ai didi

c++ - 如何在 C++ 中打印通用 map

转载 作者:太空宇宙 更新时间:2023-11-04 15:17:08 24 4
gpt4 key购买 nike

我正在尝试编写一个函数来打印通用 map 。这是我到目前为止所拥有的:

    template<typename map_key, typename map_val>
void log(DEBUG_LEVEL level, std::map<map_key, map_val> _map) {
if (level >= d_level) {
for (std::map<map_key, map_val>::iterator it = _map.begin();
it != _map.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
}
}

它不编译。

error: expected ';' before 'it'
error: 'it' was not declared in this scope
  1. 为什么不能编译?
  2. 有没有更好的写法?我找到了一个单行打印 vector here (第二个答案)我想知道是否有相同的 map ?

更新:我修复了 (1) 但仍在等待 (2) 的答案我喜欢 Galik 的回答,但是当我尝试将其添加为函数时出现错误:error:'std::ostream& Logger::operator<<(std::ostream&, const std::pair<const _Key, _Tp>&)' must take exactly one argument

这是我的 Logger 类:

extern DEBUG_LEVEL d_level;

class Logger {

public:

Logger(const char * app_name);
Logger(DEBUG_LEVEL level, char * app_name);
void log(DEBUG_LEVEL level, const char* str, ...);

template<typename vector_type>
void log(DEBUG_LEVEL level, const std::vector<vector_type>& _vec,
const std::string seperator = ", ") {
if (level >= d_level) {
std::cout << get_prefix_msg() << " ";
change_color(level);
std::cout << "[";
std::copy(_vec.begin(), _vec.end(),
std::ostream_iterator<vector_type>(std::cout,
seperator.c_str()));
std::cout << "]\n";
printf(ANSI_COLOR_RESET);
}
}

template<typename map_key, typename map_val>
void log(DEBUG_LEVEL level, const std::map<map_key, map_val>& _map,
const std::string seperator = ", ") {
if (level >= d_level) {
std::cout << get_prefix_msg() << " \n";
change_color(level);
std::cout << "[";
for (typename std::map<map_key, map_val>::const_iterator it =
_map.begin(); it != _map.end(); ++it)
std::cout << it->first << " => " << it->second << seperator;
std::cout << "]\n";
printf(ANSI_COLOR_RESET);
}
}

/**
* will log but without the application _app_name and without the debug level (but will have the right color)
*/
void strip_log(DEBUG_LEVEL level, const char* str, ...);

void change_verbosity(DEBUG_LEVEL level);

static int msg_id;
private:
const char * _app_name;
void change_color(DEBUG_LEVEL level, bool is_strip = false);
int get_next_msg_id();
std::string get_prefix_msg();
static DEBUG_LEVEL d_level;

};

最佳答案

typename 丢失。应该是

template<typename map_key, typename map_val>
void log(DEBUG_LEVEL level, const std::map<map_key, map_val>& _map) {
if (level >= d_level) {
for (typename std::map<map_key, map_val>::const_iterator it = _map.begin(); it != _map.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
}
}

或者在 C++11 中

template<typename map_key, typename map_val>
void log(DEBUG_LEVEL level, const std::map<map_key, map_val>& _map) {
if (level >= d_level) {
for (const auto& p : _map)
std::cout << p.first << " => " << p.second << '\n';
}
}

关于c++ - 如何在 C++ 中打印通用 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29961856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com