std::_Xout_of_range Error when accessing value by key in map

0

I have a problem that I really don't get. Maybe I didn't understand some basics of C++, which I actually thought I did. I basically only want to get a pointer to a set out of a map:

map<string, set<string>*>* ma = WindowCollection::testCase->getItems();
string te = ui->labelLeftUp->text().toStdString();
set<string>* itemSet = ma->at(te);

When debugging I get the following error in line 3:

Exception at 0x7ff83de9a1c8, code: 0xe06d7363: C++ exception, flags=0x1 (execution cannot be continued) (first chance) in MSVCP120D!std::_Xout_of_range

Exception at 0x7ff83de9a1c8, code: 0xe06d7363: C++ exception, flags=0x1 (execution cannot be continued) in MSVCP120D!std::_Xout_of_range

This says that the requested set isn't in the map under the given key. Here are my variables from the debugging view, when the exception is thrown:

enter image description here

I really don't get it. te "Ich" obviously is a key in ma. What's the problem? Also going one step deeper into map:

mapped_type& at(const key_type& _Keyval)
        {   // find element matching _Keyval
        iterator _Where = this->lower_bound(_Keyval);
        if (_Where == this->end()
            || this->_Getcomp()(_Keyval, this->_Key(_Where._Mynode())))
            _Xout_of_range("invalid map<K, T> key");
        return (_Where->second);
        }

enter image description here

The exception is thrown in the last line. It's the same. Keyval "Ich" has a value assigned and ist represented by the key value pair 2.

c++
nullpointerexception
stdmap
asked on Stack Overflow Nov 11, 2016 by Averius

1 Answer

0

std::map::at method is good when you sure the key exists in the map. It's not the case here. On the screenshots above the key value in the map is "Ich", but the value of the te variable is "Ich ".

Space at the end of te variable is the reason of the problem.

You can use std::map::find or std::map::count to check if the key exists in the map.

answered on Stack Overflow Nov 11, 2016 by Nikita

User contributions licensed under CC BY-SA 3.0