2013-05-29 98 views
-4

我試圖將字符串添加到矢量字符串矢量的末尾,並以某種方式遇到了內存問題。將字符串添加到矢量的矢量

我的代碼與此類似

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

'slist.back()'更好,但我們需要一個SSCCE。我不相信你已經展示了正確的代碼。 – chris

+11

「內存問題」?什麼樣的記憶問題?你遇到了什麼錯誤?您向我們展示了我們不能用來重現問題的代碼,並表示您在未告知我們錯誤* *的情況下會得到一個錯誤。在這種情況下,我可以給出的最具體的答案是「可能有一種方法可以使代碼正常工作」 – jalf

回答

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); 

問題可能在其他地方。你的調試器說什麼?

+0

humm ...多數民衆贊成在很奇怪...如果這段代碼是在for循環,它會影響結果? – user1948847

+1

@ user1948847,真的,發佈[sscce](http://sscce.org)。這並不難,而且更有價值。 – chris

+0

@ user1948847 - 將代碼放在循環中工作正常:https://ideone.com/xgO0ty – Bill