将字符串添加到矢量矢量

时间:2013-05-29 20:36:13

标签: c++ memory vector

我试图在字符串向量的向量末尾添加一个字符串,并以某种方式遇到内存问题。

我的代码与此类似

vector<vector<string>> slist;

....

slist.push_back(vector1);
slist.push_back(vector2);

...

for(int i=0; i<10; i++){
    int length = slist.size()-1;
    slist[length].push_back("String"); // also tried slist.back().push_back("S");
}

而这一些如何给我一个记忆问题

Invalid read of size 8
==2570==    at 0x404D18: std::vector<std::string, std::allocator<std::string>              >::push_back(std::string const&) (stl_vector.h:735)
==2570==    by 0x403956: main (asm.cc:400)
==2570==  Address 0xfffffffffffffff0 is not stack'd, malloc'd or (recently) free'd
==2570==
==2570==
==2570== Process terminating with default action of signal 11 (SIGSEGV)
==2570==  Access not within mapped region at address 0xFFFFFFFFFFFFFFF0
==2570==    at 0x404D18: std::vector<std::string, std::allocator<std::string> >::push_back(std::string const&) (stl_vector.h:735)
==2570==    by 0x403956: main (asm.cc:400)
==2570== 

谁能告诉我为什么?

PS:对于之前提出质疑的问题感到抱歉..

1 个答案:

答案 0 :(得分:1)

您提供的代码works fine

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

using namespace std;

void print(vector<vector<string>> s)
{
    cout << "Lists:" << endl;
    for (const auto& v : s)
    {
        cout << "List: ";
        for (const auto& i : v)
        {
            cout << i << ", ";
        }
        cout << endl;
    }
    cout << "Done" << endl;
}

int main()
{
    vector<vector<string>> slist;

    slist.push_back(vector<string>());
    slist.push_back(vector<string>());

    print(slist);

    const auto length = slist.size()-1;
    slist[length].push_back("String"); // also tried slist.back().push_back("S");

    print(slist);
}

编辑:是的,你甚至可以把它into a loop

vector<vector<string>> slist;

print(slist);

for (auto i = 0; i < 7; ++i)
{
    slist.push_back(vector<string>());
    for (auto j = 0; j < 5; ++j)
    {
        slist[i].push_back("String[" + toStr(i) + "][" + toStr(j) + "]"); // also tried slist.back().push_back("S");
    }
}

print(slist);

问题可能在其他地方。你的调试器说了什么?