开发者

Segfault in map

I can't understand why does this code fail with segfault:

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

using namespace std;

int main(int argc, char** argv) {

    map <string, string> temp;
    map <string, string>::iterator it;

S

string text = ""; string thatChange = ""; string whatChange = "";

    getline (cin, text);


    while (true)
    {
        getline (cin, thatChange);
        if (thatChange == "-1")
            break;

        getline (cin, whatChange);
        temp.insert(pair <string, string> (thatChange, whatChange));
    }

    for (int i = 0; i < temp.size(); i++)
    {
        string thatChange = it->first ; // thatChange
        string whatChange = it->second; // whatChange
        it++;

        int index = text.find(thatChange);
        text.erase(index, thatChange.size());
        text.insert(index, whatChange);
    }

    cout << "text\n"<< text;

    return 0;
}

UPD: Debugger says:

No sourc开发者_C百科e available for "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string() at 0x7ffff7b75928" 


string thatChange = it->first ;

This line invokes UB. The it has never been initialized so far. You ought to initialize this as follows:

it = tmp.begin();

and to iterate over all the elements of the map use:

for (map<string, string>::const_iterator f = temp.begin(), e = temp.end;
     f != e;
     ++f) {
   // ....
}


FWIW the code snippet compiles and runs fine with VS2010 so if you got an error the problem is probably located elsewhere.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜