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

maintenant je veux une nouvelle chaîne à être le iterator (ces 3 versions ne fonctionnera pas)std :: Liste <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 doit être la chaîne * mais ça ne marche pas, j'ai besoin d'aide!

+3

Pourquoi utilisez-vous des pointeurs? –

+1

Il n'est pas clair dans votre message ce que vous essayez d'accomplir. Vous aider à résoudre les erreurs du compilateur ne va pas vraiment être utile, n'est-ce pas? –

+0

Que voulez-vous dire par "Je veux une nouvelle chaîne pour être l'itérateur"? Cela n'a aucun sens, tout comme "Je veux qu'une nouvelle pomme soit l'avion". –

Répondre

0

En C++ moderne, nous préférons (nous devrions) nous référer aux données par valeur ou référence. Idéalement, pas par pointeur sauf si nécessaire en tant que détail d'implémentation.

Je pense que ce que vous voulez faire quelque chose comme ceci:

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

Résultats escomptés:

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