简体   繁体   中英

C++ multimap<int, vector<string>> memory allocation issue

I am wondering how to resolve this problem where the vectors (vec, vec2) are destroyed after exiting storeData(), which causes a segmentation fault in main(). Should I allocate memories for each vector (vec, vec2)? If so, which is the best way to do it? Also, how could I delete them after? Thank you.

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

using namespace std;

void storeData();

multimap<int, vector<string> > mypairs;

void storeData()
{
    vector<string> vec;
    vec.push_back("one");
    vec.push_back("two");

    vector<string> vec2;
    vec2.push_back("alpha");
    vec2.push_back("beta");

    mypairs.insert(make_pair(1, vec));
    mypairs.insert(make_pair(2, vec2));
}

int main(int, char**)
{
    storeData();

    string str;
    vector<string>::const_iterator it;
    multimap<int, vector<string> >::const_iterator res;
    res = mypairs.find(1);
    for(it = res->second.begin(); it < res->second.end(); it++) {
        str = *it;
    }
    //use string str to do something else later...
}

vec and vec2 will be copied into mypairs , so it doesn't matter if the original objects are destroyed.

You should post more information about the segfault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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