2017-10-13 98 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" 
相关问题