2017-10-13 130 views
-3
std::list<std::string> lWords; //filled with strings! 
for (int i = 0; i < lWords.size(); i++){ 
    std::list<std::string>::iterator it = lWords.begin(); 
    std::advance(it, i); 

現在我想一個新的字符串是迭代器(這3個版本將無法正常工作)的std ::列表<std::string> ::迭代器的std :: string

std::string * str = NULL; 

    str = new std::string((it)->c_str()); //version 1 
    *str = (it)->c_str(); //version 2 
    str = *it; //version 3 


    cout << str << endl; 
} 

STR應該是字符串*但它不起作用,需要幫助!

+3

你爲什麼使用指針? –

+1

從你的文章中不清楚你想要完成什麼。幫助你解決編譯錯誤並不會真的有用,是嗎? –

+0

你是什麼意思「我想要一個新的字符串是迭代器」?這是沒有道理的,就像「我想要一個新的蘋果成爲飛機」一樣。 –

回答

0

在現代C++中,我們(應該)傾向於通過值或引用來引用數據。理想情況下不要使用指針,除非必要作爲實現細節。

我想你想要做的是這樣的:

#include <list> 
#include <string> 
#include <iostream> 
#include <iomanip> 

int main() 
{ 
    std::list<std::string> strings { 
     "the", 
     "cat", 
     "sat", 
     "on", 
     "the", 
     "mat" 
    }; 

    auto current = strings.begin(); 
    auto last = strings.end(); 

    while (current != last) 
    { 
     const std::string& ref = *current; // take a reference 
     std::string copy = *current; // take a copy 
     copy += " - modified"; // modify the copy 

     // prove that modifying the copy does not change the string 
     // in the list 
     std::cout << std::quoted(ref) << " - " << std::quoted(copy) << std::endl; 

     // move the iterator to the next in the list 
     current = std::next(current, 1); 
     // or simply ++current; 
    } 

    return 0; 
} 

預期輸出:

"the" - "the - modified" 
"cat" - "cat - modified" 
"sat" - "sat - modified" 
"on" - "on - modified" 
"the" - "the - modified" 
"mat" - "mat - modified" 
相關問題