search

Home  >  Q&A  >  body text

c++ - Question about forward_list using iterator to output elements

#include "iostream"
#include "forward_list"
#include "string"

using namespace std;

int main() {
    
    forward_list<int> fl1 = { 1, 2, 3 };
    for (auto iter = fl1.begin(); iter != fl1.end(); ++iter) {
        cout << *iter << " ";
    }
    cout << endl;
    //以上都是没什么问题的,在控制台会打印出1 2 3
    //但是……
    
    forward_list<string> fl2 = { "hello", "world", "Cpp" };
    for (auto iter = fl2.begin(); iter != fl2.end(); ++iter) {
        cout << *iter << " "; //这里VS报错没有对应<<的元素, 请问这是为什么?
        //而且当我用printf(%s, *iter)打印时虽然编译器不报错但是输出的结果却是乱码……
    }
    cout << endl;

    return 0;
}
过去多啦不再A梦过去多啦不再A梦2760 days ago683

reply all(1)I'll reply

  • PHPz

    PHPz2017-05-31 10:41:45

    g++ 6.3.0 x86_64-posix-seh-rev2 No problem
    clang++ 4.0.0 Target: x86_64-pc-windows-msvc No problem
    In this case, use for(const auto& item : list) More OK.

    reply
    0
  • Cancelreply