Invalid std :: map insert behavior

I get strange behavior when inserting values ​​into a map: I always insert at the end of a map, but sometimes records fail.

If I do a direct test, then I have no problem - the numbers are correctly ordered:

map<int,int> testMap;
for(int i = 0; i < 100; ++i)
{
    // everything is ordered correctly here
    testMap.insert(testMap.end(), pair<int,int>(i,i));
}

But when I parse the line, and I try to insert the values ​​in the same order as I read them, then everything does not work out so well:

const string INPUT_TWO =
"=VAR STRING1 \"MYSTRING\"\n\
=VAR STRING2 \"EXAMPLE\"\n\
=VAR NUMBER1 12345\n\
=VAR NUMBER2 23456\n\
=VAR DUMMY 1111\n";

const string VAL_STRING = "VAR";

vector<pair<string, string>> parse_fields(const string & input)
{
    map<string, string> fieldsMap;
    vector<pair<string, string>> sequenceFields;
    vector<string> lines = split(input, '\n');
    for(size_t i = 0; i < lines.size(); ++i)
    {
        if(lines[i].find(VAL_STRING)!=string::npos)
        {
            vector<string> vals = split(lines[i], ' ');
            if(vals.size()==3)
            {
                fieldsMap.insert(fieldsMap.end(), pair<string,string>(vals[1], remove_quotes(vals[2])));
                sequenceFields.push_back(pair<string,string>(vals[1], remove_quotes(vals[2])));
            }
        }
    }

    // at the end the map looks like:
    // "DUMMY", "1111"
    // "NUMBER1", "12345"
    // "NUMBER2", "23456"
    // "STRING1", "MYSTRING"
    // "STRING2", "EXAMPLE"

    // the vector of pairs looks like:
    // "STRING1", "MYSTRING"
    // "STRING2", "EXAMPLE"
    // "NUMBER1", "12345"
    // "NUMBER2", "23456"
    // "DUMMY", "1111"

    return sequenceFields;
}

For your reference, I pasted all the extra code in pastie .

Does anyone know why this might happen?

+3
source share
2 answers

A std::map - , . , , Boost.MultiIndex.

+4

. -. ++ std::map . . http://www.cplusplus.com/reference/stl/map/. , .

, . unordered_map, (. http://en.wikipedia.org/wiki/Unordered_map_%28C%2B%2B%29; hash_map, , ). .

+1

Source: https://habr.com/ru/post/1753992/


All Articles