排序 2022-12-12 15:34 采纳率: 100%
浏览 12
已结题

C++ 标准算法for_each问题

我注释掉了for_each那一行,取消注释后编译器会在编译期报错。
要怎么才能利用for_each输出vector容器的值呢?

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
//常用遍历算法    transform

class Transfrom    //搬运
{
public:
    int operator()(int v)
    {
        return v;
    }
};

class MyPrint    //函数对象,功能为打印
{
    void operator()(int val)
    {
        cout << val << " ";
    }
};

void test01()
{
    vector<int>v;
    for (int i = 0; i < 10; ++i)
    {
        v.push_back(i);
    }

    vector<int>vTarget;

    vTarget.resize(v.size());    //目标容器    需要提前开辟空间

    transform(v.begin(), v.end(), vTarget.begin(), Transfrom());

    //for_each(vTarget.begin(), vTarget.end(), MyPrint());//如果不注释本行则报错
    cout << endl;
}
int main()
{
    test01();
    system("pause");
    return 0;
}

  • 写回答

1条回答 默认 最新

  • 排序 2022-12-12 15:46
    关注

    已解决。
    忘记写公共属性了

    class MyPrint    //函数对象,功能为打印
    {
    public:
        void operator()(int val)
        {
            cout << val << "\t";
        }
    };
    
    
    评论

报告相同问题?

问题事件

  • 系统已结题 12月20日
  • 创建了问题 12月12日

悬赏问题

  • ¥15 关于#python#的问题:需要代写样例autojs的自动输入图形验证码的请专家们教程以下
  • ¥15 ruoyi-vue-plus操作失败
  • ¥15 微信小程序分页查询如何设置下一页
  • ¥15 树莓派Linux系统下无法下载miniconda
  • ¥15 C# wpf 软年 卸载有残留 webview2
  • ¥15 求代写matlab解决柔性调度代码,价格私
  • ¥15 为什么安装Anaconda时报系统找不到指定文件?
  • ¥15 如何将这个项目的ssh-TCP,改成ssh3-UDP协议
  • ¥20 ic卡dump文件校检码解密
  • ¥15 关于:接收到的数据不是有效的JSON格式