【问题标题】:std::list<std::string>::iterator to std::stringstd::list<std::string>::iterator 到 std::string
【发布时间】:2017-10-13 16:59:33
【问题描述】:
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 应该是字符串 *it 但这不起作用,需要帮助!

【问题讨论】:

  • 你为什么使用指针?
  • 从您的帖子中不清楚您要完成什么。帮助您解决编译器错误并没有真正的用处,不是吗?
  • “我想要一个新字符串作为迭代器”是什么意思?这毫无意义,就像“我想要一个新苹果当飞机”。
  • 您只是想要std::string str = *it;std::string&amp; str = *it; 之类的东西吗?你为什么要使用new

标签: c++ string list stl iterator


【解决方案1】:

在现代 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"

【讨论】:

    猜你喜欢
    • 2011-03-26
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多