2017-10-13 4 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); 

jetzt will ich eine neue Saite der Iterator (diese drei Versionen funktionieren nicht) seinstd :: list <std::string> :: iterator 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 die Zeichenfolge sein sollte * es funktioniert aber nicht, brauche Hilfe!

+3

Warum Sie verwenden Zeiger? –

+1

Es ist nicht klar aus Ihrem Beitrag, was Sie erreichen möchten. Ihnen bei der Behebung von Compiler-Fehlern zu helfen, wird nicht wirklich nützlich sein, oder? –

+0

Was meinen Sie mit "Ich möchte eine neue Zeichenfolge als Iterator"? Es macht keinen Sinn, genauso wie "Ich möchte, dass ein neuer Apfel das Flugzeug ist". –

Antwort

0

In modernen C++ sollten wir (lieber) auf Daten nach Wert oder Referenz verweisen. Idealerweise nicht per Zeiger, wenn es nicht als Implementierungsdetail notwendig ist.

Ich denke, was Sie tun möchten, so etwas wie dieses:

#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; 
} 

erwartete Ausgabe:

"the" - "the - modified" 
"cat" - "cat - modified" 
"sat" - "sat - modified" 
"on" - "on - modified" 
"the" - "the - modified" 
"mat" - "mat - modified" 
Verwandte Themen