简体   繁体   中英

Double Vector issue in c++

So I was looking to make basically a double array but have it be dynamic via vectors. However I guess I do not fully understand this as I am doing something wrong causing my vector to be subscript out of range. Here below is my code:

std::vector<std::vector<std::string>> m_menuList;
m_menuList[0].push_back(menuType);
m_menuList[0].push_back(location);

This might be a stupid mistake or something completely wrong, it does compile correctly, just always crashes.

Thanks!

We tend to call "double vectors" 2D Vectors. A "triple vector" would then be a 3D Vector and so on...the whole lot of them can be called Multidimensional Vectors.

Your issue is that the outer vector is empty, so there is no m_menuList[0] . You could instead do:

m_menuList.push_back(std::vector<std::string>(1, menuType));

Which will push a vector consisting solely of menuType to the back of m_menuList .

You can also start m_menuList off with a certain number of empty vectors so that your current code would work (assuming you have some integer n):

std::vector<std::vector<std::string>> m_menuList(n);

You have to resize() your vector after initialization before accessing it using index.

std::vector<std::vector<std::string>> m_menuList;
m_menuList.resize(1);

But when you insert objects you dont need index, you can do as follows:

m_menuList.push_back(menuType);
m_menuList.push_back(location);

OR

std::vector<std::vector<std::string>> m_menuList;
m_menuList.push_back(menuType);
m_menuList.push_back(location);

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