gpt4 book ai didi

c++ - make_pair 是在栈上还是堆上?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:02:48 28 4
gpt4 key购买 nike

如果我从不同的范围将它插入到 map 中,是否需要分配一对?

#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 从该对创建一个新对象,并将其放入 map 中。 map 会存储此拷贝,直到 map 被销毁或元素从 map 中移除。

关于c++ - make_pair 是在栈上还是堆上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8982706/

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