Effective STL 笔记

    技术2022-05-11  20

    Item6: 警惕C++最令人恼怒的解析

    //代码1 #include "stdafx.h" #include <string> #include <iostream> #include <fstream> #include <vector> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { ifstream dataFile("list.data"); vector<string> strv(istream_iterator<string>(dataFile), istream_iterator<string>()); strv.push_back("hello"); }

    本代码想通过vector的初始化函数对strv进行初始化,初始化的内容为dataFile文件的内容。

    进一步说明初始化参数的意义:

    //代码2 #include "stdafx.h" #include <string> #include <iostream> #include <fstream> #include <vector> #include <algorithm> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { vector<string> strv; copy(istream_iterator<string>(cin), istream_iterator<string>(), back_inserter(strv)); copy(strv.begin(), strv.end(), ostream_iterator<string>(cout)); }

    编译执行代码一,发现里面说push_back需要一个联合体。因此可知系统并没有将其解释vector类。

    函数声明:

    int f(double d);int f(double (d));

    int f(double);

    以函数为参数的函数:

    int g(double (*pf)());

    int g(double pf());

    int g(double ());

    现在我们对以函数为参数的函数进行扩展

    int g(double ())

    -> vector<string>  g(double ())

    -> vector<string> g(double (d), double())

    ->vector<string> g(istream_iterator<string>(d), istream_iterator<string>()

    ->vecotr<string> strv(istream_iterator<string>(dataFile), istream_iterator<string>());

    由此可知,这条语句也可以解释为函数申明


    最新回复(0)