简体   繁体   中英

vector of list of string in cpp, “EXC_BAD_ACCESS”

#include <iostream>
#include <vector>
#include <list>
using namespace std;
int main()
{
    vector<list<string> > testList;
    testList[2].push_back("ADA");
    return 0;
}

It got a thread, when program running. signal: "EXC_BAD_ACCESS"

I guesse it's because of illegal memory access, but I don't know why and how to fix it.

thanks so much

testList has length 0 after initialization, therefore you cannot access testList[2] .

You can pass an initial size to the c'tor of std::vector, so the following should work

vector<list<string> > testList(3);
testList[2].push_back("ADA");

您的testList大小为0,因此您无法访问元素2.因为您需要调整它的大小:

testList.resize(3);

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