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

312 Views Asked by At

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...
}
1

There are 1 best solutions below

4
On

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.