简体   繁体   English

从函数返回对地图的引用

[英]Returning a reference to a map from a function

What is the standard practice of creating a map and returning it to a function as a reference?创建地图并将其返回给函数作为参考的标准做法是什么?

In my example, I am just creating a hashmap of the character count from a string, and doing this twice.在我的示例中,我只是从字符串创建字符数的哈希图,并执行两次。 I see that to return it from the function, the map would have to be created dynamically, otherwise, it would go out of scope and lead to undefined behavior.我看到要从函数返回它,必须动态创建映射,否则,它将超出范围并导致未定义的行为。

However, I don't know how to add to the map, with just a pointer to it.但是,我不知道如何添加到地图,只有一个指向它的指针。 (see code map[*it] += 1; ), and I'm not sure if I'm going about the process in the correct way. (请参阅代码map[*it] += 1; ),我不确定我是否以正确的方式进行该过程。

#include <iostream>
#include <map>


std::map<char, int>& createMap(std::string& myString){
    std::map<char, int>* map = new std::map<char, int>();
    for(std::string::iterator it = myString.begin(); it != myString.end(); ++it){
        map[*it] += 1;
    }
    return map;
}

void turnStringsIntoMaps(std::string a, std::string b){
    std::map<char, int> firstMap = createMap(a);
    std::map<char, int> secondMap = createMap(b);
    for(auto it = m.begin(); it != m.end(); ++it){
        std::cout << it->first << " : " << it->second << '\n';
        std::cout << m[it->first] << '\n';
    }
    return true;
}

What is the standard practice of creating a map and returning it to a function as a reference?创建地图并将其返回给函数作为参考的标准做法是什么?

There is no "standard practice" of what you want to do, because, frankly, it is unusual.您想要做什么没有“标准做法”,因为坦率地说,这是不寻常的。

When you want a function to return a map then make it return a map:当您希望函数返回地图时,请使其返回地图:

std::map<char, int> createMap(std::string& myString){
    std::map<char, int> myMap;
    // ...
    return myMap;
}

Returning a reference to a local variable is usually a problem:返回对局部变量的引用通常是一个问题:

int& foo() { int x; return x; }

because the reference returned is dangling (the x is long gone when the caller gets the reference).因为返回的引用是悬空的(当调用者获得引用时, x早已消失)。 For more on that read here .有关更多信息,请阅读此处

It seems you tried to workaround that problem by using dynamic memory allocation.您似乎试图通过使用动态内存分配来解决该问题。 However, this is not necessary.然而,这不是必需的。 Rather it is to be avoided!而是要避免! Standard containers already manage their memory and most of the time allocating a container on the heap is a code smell.标准容器已经在管理它们的内存,而且大部分时间在堆上分配容器是一种代码味道。

Without knowing more about why you'd like to do this, you have a couple of options.在不知道更多关于为什么要这样做的情况下,您有几个选择。

#include <map>
#include <iostream>
#include <string>

std::map<char, int> CreateMap(const std::string& myString){
    std::map<char, int> new_map;
    for(const auto& it : myString){
        new_map[it] += 1;
    }
    return std::move(new_map);
}

int main()
{
    auto my_map = CreateMap(std::string("testing"));

    for (const auto& iter: my_map){
        cout << iter.first << "  " << iter.second << endl;
    }

    return 0;
}

The std::move moves the newly created map and hands it back to the caller, so the function no longer has too keep the ref alive. std::move移动新创建的地图并将其交还给调用者,因此该函数不再需要保持 ref 处于活动状态。

Another option might be to create the map on the call side, and pass it in by ref:另一种选择可能是在调用端创建映射,并通过 ref 传入:

void CreateMap(const std::string& my_string, std::map<char, int>& my_map);

Usage:用法:

std::map<char, int> my_map;
CreateMap("teststring", my_map);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM