是堆栈或堆上的make_pair

is make_pair on the stack or heap?

本文关键字:make pair 堆栈      更新时间:2023-10-16

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

#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, ...)的元素,甚至不为映射值创建临时。