c++ - 将 string::iterator 转换为 std::string

标签 c++ string iterator type-conversion

现在这让我有点困惑,但 std::string::iterator 实际上产生一个 char(由 typeid 显示)。我需要它作为一个字符串。我该怎么做?

#include <string>
#include <iterator>

int main(){
    std::string str = "Hello World!";
    for( std::string::iterator it = str.begin(); it != str.end(); it++ ){
        std::string expectsString(*it); // error
        std::string expectsString(""+*it); // not expected result
        myFunction(expectsString);
    }
}

我正在使用启用了 C++11 的 gcc 5.4.0。

编辑:因为这需要进一步澄清 我想将 *it 转换为字符串。所以我可以将当​​前迭代的字符用作字符串,而不是 char。 正如我在上面的代码示例中失败的示例所展示的那样,我正在寻找类似的东西

std::string myStr = *it; //error

最佳答案

改用

std::string expectsString(1, *it); 

这是一个演示程序

#include <iostream>
#include <string>

int main() 
{
    std::string str = "Hello World!";

    for( std::string::iterator it = str.begin(); it != str.end(); it++ )
    {
        std::string expectsString( 1, *it );
        std::cout << expectsString;
    }

    std::cout << std::endl;

    return 0;
}

它的输出是

Hello World!

关于c++ - 将 string::iterator 转换为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49051825/

相关文章:

c++ - C++中的迭代器和常量迭代器

c++ - 使用 boost::filesystem 迭代目录时可以更改文件顺序吗?

c++ - 使用 STL 和一元函数适配仿函数检查列表成员资格

c++ - 在 C++ 中计算 bit_Delta(double p1, double p2)

c++ - 从 3 级 map 的第 2 级获取所有键

c++ - 哪个版本的 "find an occurence"函数更快?

c++ - 在 C++11 中创建指针 vector 的惯用方法?

c - 具有良好字符串操作支持的可嵌入语言

c - 我的 strcpy 中的段错误

c++ - 使用函数更改 std::string 的内容