技术问询:能否将queue作为map的value?此用法是否合理?
Can I use a
queue as the value type in a std::map? 当然没问题啦!这种std::map<std::string, std::queue<std::string>>的用法完全合法且合适,C++ STL的容器设计本来就支持这种嵌套组合——只要作为map值类型的容器满足可拷贝构造和可赋值的要求,而std::queue作为标准容器适配器,天生就符合这些条件。
咱们来看你的示例代码:
#include <stdio.h> #include <string.h> #include <unistd.h> #include <map> #include <queue> using namespace std; int main(){ map<string, queue<string>> m; char temp[1024]; strcpy(temp, "hello world"); m[temp].push(temp); return 0; }
这段代码是可以正常编译并运行的,它的逻辑很清晰:
- 初始化了一个键为
std::string、值为std::queue<std::string>的map对象m - 通过C风格字符数组和
strcpy存储字符串(这里其实可以更贴合C++风格,直接用std::string temp = "hello world";会更安全简洁) - 利用
map的operator[]特性:如果键temp对应的条目不存在,会自动创建一个默认构造的std::queue<std::string>,然后调用push把字符串添加到队列里
这里给你两个小建议:
- 尽量避免使用C风格字符数组和
strcpy,改用std::string可以避免缓冲区溢出风险,代码也更易读 - 如果不想让
map自动创建不存在的键,可以先通过find方法查找键是否存在,再进行操作,比如:std::string temp = "hello world"; auto it = m.find(temp); if (it != m.end()) { it->second.push(temp); }
内容的提问来源于stack exchange,提问作者Zhang Fan
相关产品推荐
相关产品推荐

