C++ 如何从地图中获取值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10699689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:21:28  来源:igfitidea点击:

How can I get a value from a map?

c++dictionarystdmap

提问by Aneesh Narayanan

I have a mapnamed valueMapas follows:

我有一个map命名valueMap如下:

typedef std::map<std::string, std::string>MAP;
MAP valueMap;
...
// Entering data.

Then I am passing this map to a function by reference:

然后我通过引用将此映射传递给函数:

void function(const MAP &map)
{
  std::string value = map["string"];
  // By doing so I am getting an error.
}

How can I get the value from the map, which is passed as a reference to a function?

如何从作为函数引用传递的映射中获取值?

回答by Steve Jessop

Unfortunately std::map::operator[]is a non-const member function, and you have a const reference.

不幸的std::map::operator[]是,它是一个非常量成员函数,您有一个 const 引用。

You either need to change the signature of functionor do:

您需要更改function或执行以下操作的签名:

MAP::const_iterator pos = map.find("string");
if (pos == map.end()) {
    //handle the error
} else {
    std::string value = pos->second;
    ...
}

operator[]handles the error by adding a default-constructed value to the map and returning a reference to it. This is no use when all you have is a const reference, so you will need to do something different.

operator[]通过向映射添加默认构造值并返回对它的引用来处理错误。当您只有一个常量引用时,这没有用,因此您需要做一些不同的事情。

You couldignore the possibility and write string value = map.find("string")->second;, if your program logic somehow guarantees that "string"is already a key. The obvious problem is that if you're wrong then you get undefined behavior.

如果您的程序逻辑以某种方式保证这已经是一个键,您可以忽略这种可能性并写入。显而易见的问题是,如果你错了,你就会得到未定义的行为。string value = map.find("string")->second;"string"

回答by Gabe Rainbow

map.at("key") throws exception if missing key

如果缺少键,map.at("key") 会抛出异常

If k does not match the key of any element in the container, the function throws an out_of_range exception.

如果 k 与容器中任何元素的键都不匹配,则该函数会抛出 out_of_range 异常。

http://www.cplusplus.com/reference/map/map/at/

http://www.cplusplus.com/reference/map/map/at/

回答by honk

The answerby Steve Jessopexplains well, why you can't use std::map::operator[]on a const std::map. Gabe Rainbow'sanswersuggests a nice alternative. I'd just like to provide some example code on how to use map::at(). So, here is an enhanced example of your function():

答案史蒂夫·杰索普很好地解释了,为什么你不能使用std::map::operator[]一个const std::mapGabe Rainbow 的回答提出了一个不错的选择。我只想提供一些关于如何使用map::at(). 因此,这是您的增强示例function()

void function(const MAP &map, const std::string &findMe) {
    try {
        const std::string& value = map.at(findMe);
        std::cout << "Value of key \"" << findMe.c_str() << "\": " << value.c_str() << std::endl;
        // TODO: Handle the element found.
    }
    catch (const std::out_of_range&) {
        std::cout << "Key \"" << findMe.c_str() << "\" not found" << std::endl;
        // TODO: Deal with the missing element.
    }
}

And here is an example main()function:

这是一个示例main()函数:

int main() {
    MAP valueMap;
    valueMap["string"] = "abc";
    function(valueMap, "string");
    function(valueMap, "strong");
    return 0;
}

Output:

输出:

Value of key "string": abc
Key "strong" not found

键“字符串”的值:
找不到abc键“强”

Code on Ideone

Ideone 上的代码

回答by Aitor

The main problem is that operator [] is used to insert and read a value into and from the map, so it cannot be const. If the key does not exist, it will create a new entry with a default value in it, incrementing the size of the map, that will contain a new key with an empty string ,in this particular case, as a value if the key does not exist yet. You should avoid operator[] when reading from a map and use, as was mention before, "map.at(key)" to ensure bound checking. This is one of the most common mistakes people often do with maps. You should use "insert" and "at" unless your code is aware of this fact. Check this talk about common bugs Curiously Recurring C++ Bugs at Facebook

主要问题是运算符 [] 用于在映射中插入和读取值,因此它不能是 const。如果键不存在,它将创建一个带有默认值的新条目,增加地图的大小,其中将包含一个带有空字符串的新键,在这种特殊情况下,如果键不存在则作为值还不存在。从地图读取时应避免使用 operator[] 并使用之前提到的“map.at(key)”来确保边界检查。这是人们在使用地图时经常犯的最常见的错误之一。除非您的代码知道这一事实,否则您应该使用“插入”和“在”。在 Facebook查看有关常见错误的讨论Curiously Recurring C++ Bugs

回答by Chef Gladiator

How can I get the value from the map, which is passed as a reference to a function?

如何从作为函数引用传递的映射中获取值?

Well, you can pass it as a reference. The standard reference wrapperthat is.

好吧,您可以将其作为参考传递。标准参考包装器

typedef std::map<std::string, std::string> MAP;
// create your map reference type
using map_ref_t = std::reference_wrapper<MAP>;

// use it 
void function(map_ref_t map_r)
{
    // get to the map from inside the
    // std::reference_wrapper
    // see the alternatives behind that link
    MAP & the_map = map_r;
    // take the value from the map
    // by reference
    auto & value_r = the_map["key"];
    // change it, "in place"
    value_r = "new!";
}

And the test.

和测试。

    void test_ref_to_map() {

    MAP valueMap;
    valueMap["key"] = "value";
    // pass it by reference
    function(valueMap);
    // check that the value has changed
    assert( "new!" == valueMap["key"] );
}

I think this is nice and simple. Enjoy ...

我认为这很好也很简单。享受 ...