前端学C++

201 阅读2分钟

这是我参与11月更文挑战的第20天,活动详情查看:2021最后一次更文挑战

STL仿函数

C++ Premier Plus称之为functor,现在多叫做function objects,译为仿函数。 直接上个比较长的例子:

 template <class T>//  
 class TooBig { 
     private: 
         T cutoff; 
     public: 
         TooBig(const T & t) : cutoff(t) {} 
         bool operator()(const T & v) { 
             return v > cutoff; 
         } 
}; 
void outint(int n) {
    std::cout << n << " ";
} 
int main() { 
    using std::list; 
    using std::cout; 
    using std::endl; 
    TooBig f100(100);
    list yadayada = {50, 100, 90, 180, 60, 210, 415, 88, 188, 201}; 
    list etcetera {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};
    yadayada.remove_if(f100); 
    etcetera.remove_if(TooBig<int>(200)); 
    for_each(yadayada.begin(), yadayada.end(), outint); 
    cout << endl; 
    for_each(etcetera.begin(), etcetera.end(), outint); 
    cout << endl;
    return 0; 
}

这里remove_iflist的成员函数,接受一个bool值,返回为true 的元素构成的list

可以看到这里通过TooBig这个类,重载了()运算符,使得通过实例化类能够构造出一个函数,这种做法在设计模式中有涉及,称为函数工厂。实际上在JS中,这就是我们经常进行的返回一个函数的操作。

function funcFactory(x){
    return function(){
        let n = x;
        \\ 这里写具体逻辑
    }

如果想通过这种方法构造一个带参数的函数,只需这样:

class TooBig2 { 
    private: 
        T cutoff; 
    public: 
        TooBig2(const T & t) : cutoff(t) {} 
        bool operator()(const T & v) { 
            return tooBig(v, cutoff); 
        } 
};
\\ 调用
TooBig2 tB100(100);
if (tB100(x)) // 即 (tooBig(x,100)
...

其他容器

除了STL以外,C++在内置库还提供了很多容器,可通过头文件导入。多为一些有用的轮子,如complex头文件是一个复数的template,而valarray实现了线性代数中的向量,可进行向量操作。

C++ Boost

大家常常会把STL和Boost放在一起讨论。Boost被认为是一个基于STL高兼容性的一个扩展。

有经验的C++开发者们这样评价Boost:库太大了,并且耦合太重,很难分离;编译时间太长;有些与标准重叠的地方。

事实上,说了Boost这么多不好,其实是在C++发展的过程中,很多Boost的轮子被包含到标准中去了,而Boost的实现就显得太重,也不够“拥抱标准”了。