std :: list <std :: string> :: std :: string的迭代器

时间:2017-10-13 16:59:33

标签: c++ string list stl iterator

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::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应该是字符串*但它不起作用,需要帮助!

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"