是堆栈或堆上的make_pair
is make_pair on the stack or heap?
如果我将一对插入到不同范围的映射中,是否需要分配它?
#include <iostream>
#include <string>
#include <unordered_map>
#include <utility>
using namespace std;
void parseInput(int argc, char *argv[], unordered_map<string, string>* inputs);
int main(int argc, char *argv[])
{
unordered_map<string, string>* inputs = new unordered_map<string, string>;
parseInput(argc, argv, inputs);
for(auto& it : *inputs){
cout << "Key: " << it.first << " Value: " << it.second << endl;
}
return 0;
}
void parseInput(int argc, char *argv[], unordered_map<string, string>* inputs)
{
int i;
for(i=1; i<argc; i++){
char *arg = argv[i];
string param = string(arg);
long pos = param.find_first_of("=");
if(pos != string::npos){
string key = param.substr(0, pos);
string value = param.substr(pos+1, param.length()-pos);
inputs->insert( make_pair(key, value) );//what happens when this goes out of scope
}
}
for(auto& it : *inputs){
cout << "Key: " << it.first << " Value: " << it.second << endl;
}
}
make_pair(key, value)
返回一个临时对象。该对象的生存期结束于创建它的完整表达式的末尾(基本上是分号)。
函数insert
从该对中创建一个新对象,并将其放入映射中。地图会存储此副本,直到地图被销毁或元素从地图中删除为止。
它的罚款:
inputs->insert( make_pair(key, value) );//what happens when this goes out of scope
std::make_pair按值返回结果。
以上影响与相同
inputs->insert( std::pair<std::string, std::string>(key, value) );
在这两种情况下,传递给insert()的值都被复制(或移动)到映射中。
不,你很好;整个地图条目值,包括键值和映射值,在插入时被复制到地图数据结构中(有时被移动)。
在C++11中,通过m.emplace(key_value, mapped_value);
插入元素的方法稍微直接一些,它甚至不创建临时pair
,或者更好的是,m.emplace(key_value, arg1, arg2, ...)
,它插入具有关键字key_value
和映射值mapped_type(arg1, arg2, ...)
的元素,甚至不为映射值创建临时。
相关文章:
- 是否需要删除包含对象的"pair"?
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 为什么大多数 pair 实现默认不使用压缩(空基优化)?
- 使用 make 编译 MPI,几个命名空间错误,例如"错误:未知类型名称'使用'?
- make 命令如何避免重新编译未更改的源文件?
- 对 pair<pair<int,int>pair<int,int unordered_map进行哈希处理>>
- MAKE:找不到包含的用户定义的头文件?
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 'make check' GLIBC 运行时的链接问题
- 删除字符串中具有相同值的任何相邻字母"pair"
- Qt5 [make -snap] 无法正确编译:进程"/usr/bin/snap"代码 1 退出
- 当我尝试定义这个向量时<pair<int , pair<int, int> > > vp(n)
- mingw32-make 使用"MinGW Makefiles"生成器跟踪 CMAKE 无法将可执行文件链接到对象库
- 如何从map<pair<string,int>,pair<string,Array>>中迭代和查找?
- make 命令创建 .file,但不创建应用程序文件
- 如何摆脱导入的 make 项目中的 Eclipse 索引器"Type std::... could not be resolved"错误
- Qt Creator 在执行步骤 "make" 时出现编译错误,-fno-stack-limit
- 如何使用MySQL Connector and Make设置C++项目
- 使用 make 将对象文件放在特定目录中