天天看点

《C++ Primer》学习笔记:迭代器介绍

《C++Primer》(第五版)中,3.4.1的例题中使用一个名为text的字符串向量存放文本文件中的数据,输出text中的内容,刚开始我这样写:

#include <iostream>
#include <string>
#include <vector>
#include <iterator>


using namespace std;

int main(){
    string text("name");
    for (auto it = text.cbegin();
        it != text.cend() && !it ->empty(); ++it)
        cout << *it << endl;
    return 0;
}      

结果报错:

error: member reference base type 'const char' is not a structure or
      union      

将string text("name");改为 const vector<string> text{"name"};就不会出错了。需要注意的是加上#include<iterator>头文件。

原因我想可能是const char*指向string对象,但是却不含member function,,后面用到的(*it).empty()的class type中需要用到member function,所以才报错。

继续阅读