zoukankan      html  css  js  c++  java
  • 函数调用运算符

    14.34定义一个函数对象类,令其执行if-then-else的操作;该类型的调用运算符接受三个参数,它首先检查第一个形参,如果成功返回第二个参数的值;如果不成功返回第三个形参的值。

    #include<iostream>
    using namespace std;
    class if_then_else
    {
    public:
        int operator()(int a,int b,int c) const
        {
            if(a)
                return b;
            else
                return c;
        }
    };
    
    int main()
    {
        if_then_else f;
        cout<<f(3,4,5)<<endl;
        return 0;
    }

    14.35 编写PrintString的类,令其从istream中读取一行输入,然后返回一个表示我们所读内容的string。如果读取失败,返回空string。

    #include<iostream>
    #include<string>
    #include<vector>
    using namespace std;
    
    class PrintString
    {
    public:
        PrintString(ostream &o=cout,char c=' '):os(o),sep(c) {}
        void operator()(const string &s) { os<<s<<sep;}
    private:
        ostream &os;
        char sep;
    };
    
    int main()
    {
        string str;
        PrintString p;
        if(getline(cin,str))
            p(str);
        else
            p(string());
        return 0;
    }

    14.36 使用上面定义的类读取标准输入,将每一行保存在vector的一个元素。

    #include<iostream>
    #include<string>
    #include<vector>
    using namespace std;
    
    class PrintString
    {
    public:
        PrintString(ostream &o=cout,istream &i=cin,char c=' '):os(o),is(i),sep(c) {}
        void operator()(const string &s) { os<<s<<sep;}
        istream& operator()(string &s) { getline(is,s); return is;}
    private:
        ostream &os;
        istream &is;
        char sep;
    };
    
    int main()
    {
        vector<string> vec;
        string str;
        PrintString p;
        while(p(str))//输入
            vec.push_back(str);
        for(const auto  v:vec)
            p(v);//输出
        /*if(getline(cin,str))
            p(str);
        else
            p(string());*/
        return 0;
    }

    14.37编写一个类令其检查两个值是否相等。使用该对象及标准库算法编写程序,令其替换某个序列中具有给定值的所有实例。

    #include<iostream>
    #include<string>
    #include<vector>
    #include<algorithm>
    using namespace std;
    
    class replaces
    {
    public:
        replaces(string s1="old",string s2="new"):oldval(s1),newval(s2) {}
        void operator()(string &s){ if(s==oldval) s=newval;}
    private:
        string oldval;
        string newval;
    };
    
    int main()
    {
        vector<string> vec={"old","a","old","b","old"};
        for_each(vec.begin(),vec.end(),replaces());
        for(auto v:vec)
            cout<<v<<" ";
        cout<<endl;
        return 0;
    }
  • 相关阅读:
    Android 中的通知
    Android 画图之Matrix(二)
    Android 画图之 Matrix(一)
    Android 实现书籍翻页效果(转载链接)
    Android 基于TranslateAnimation 的动画动态菜单(非系统menu菜单)
    Activity 页面切换的效果
    Android 访问本地API doc较慢
    Eclipse插件工具
    Android 性能优化的一些方法
    Android JAVA代码执行shell命令
  • 原文地址:https://www.cnblogs.com/wuchanming/p/3936084.html
Copyright © 2011-2022 走看看