免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1366 | 回复: 1
打印 上一主题 下一主题

stl中的函数对象的问题,求解!!! [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-03-25 10:53 |只看该作者 |倒序浏览
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;

struct Sub : public unary_function<int,void>
{
     void operator() (int & ri)
     {
         ri -= 5;
     }
};

int main()
{
     int a[10]={0,1,2,3,4,5,6,7,8,9};
     copy(a,a+10,ostream_iterator<int>(cout," ");
     cout << endl;
         
     for_each(a,a+10,Sub());
         
     copy(a,a+10,ostream_iterator<int>(cout," ");
     cout << endl;
     return 0
}
以上代码用g++编译通过,豪无问题

#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <set>
using namespace std;

struct check_unary: public unary_function<int,void>{
        void operator()(int& i){
                i -= 5;
        }
};

int main(){
        set<int> c;
        for(int i =0; i < 10; ++i)
                c.insert(i);

        for(set<int>::const_iterator pos = c.begin(); pos != c.end(); ++pos)
                cout<< *pos<<' ';
        cout<<endl;

        for_each(c.begin(), c.end(), check_unary());

        for(set<int>::const_iterator pos = c.begin(); pos != c.end(); ++pos)
                cout<< *pos<<' ';
        cout<<endl;

        return 0;
}
但我将数组换成容器后就编译通不过了
报错为:
myfuc_practice.cpp:41:   instantiated from here
/usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h:159:
error: no match for call to ‘(check_unary) (const int&
myfuc_practice.cpp:27: note: candidates are: void check_unary:perator()(int&

才学stl的新手
求解!!!!!!
谢谢!!!!!

论坛徽章:
0
2 [报告]
发表于 2008-03-31 00:50 |只看该作者
因为 set 属于关联容器的一种,它的元素是不能被修改的,所以不能用作能改变容器的算法的目的容器。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP