简体   繁体   English

C ++多图 <int, vector<string> &gt;内存分配问题

[英]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(). 我想知道如何解决这个问题,其中退出storeData()后向量(vec,vec2)被破坏,这会导致main()中的分段错误。 Should I allocate memories for each vector (vec, vec2)? 我应该为每个向量(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. vecvec2将被复制到mypairs ,因此原始对象是否被破坏都没有关系。

You should post more information about the segfault. 您应该发布有关段错误的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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