weixin_48929792 2023-09-09 14:00 采纳率: 100%
浏览 12
已结题

为什么一个提示not decleared,一个没有提示

在c++ primer plus 里程序清单16.15,为什么里面的 for_each函数不需要加std:: 就可以运行。

// functor.cpp -- using a functor
#include <iostream>
#include <list>
#include <algorithm>

template<typename T>
class TooBig
{
    private:
        T cutoff;
    public:
        TooBig(const T & t ) : cutoff(t) {}
        bool operator()(const T & v) {return v > cutoff;}
};

void outint(int x) {std::cout << x << " ";}
int main()
{
    using std::list;
    using std::cout;
    using std::endl;

    int vals[10] = {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};
    list<int> yadayada(vals, vals + 10);
    list<int> etcetera {50, 100, 90, 180, 60, 210, 415, 88, 188, 201};
    cout << "Original lists:\n"
         << "  yadayada:";
    for_each(yadayada.begin(), yadayada.end(), outint);
    cout << endl;
    cout << "  etcetera:";
    for_each(etcetera.begin(), etcetera.end(), outint);
    cout << endl;
    
    TooBig<int> f100(100);
    yadayada.remove_if(f100);
    etcetera.remove_if(TooBig<int>(200));
    cout << "Trimmed lists:\n" << "  yadayada(trimmed(>100)):";
    for_each(yadayada.begin(), yadayada.end(), outint);
    cout << endl << "  etcetera(trimmed(>200)):";
    for_each(etcetera.begin(), etcetera.end(), outint);
    cout << endl;
    return 0;
}
结果是:
Original lists:
  yadayada:50 100 90 180 60 210 415 88 188 201 
  etcetera:50 100 90 180 60 210 415 88 188 201 
Trimmed lists:
  yadayada(trimmed(>100)):50 100 90 60 88 
  etcetera(trimmed(>200)):50 100 90 180 60 88 188 

而随后我自己实验了一个小的程序,为什么就必须说for_each没有声明:
  needstd.cpp:13:2: error: ‘for_each’ was not declared in this scope
  for_each(a, a + 6, outint);
无法通过,同样的include 同样的using std::,为什么呢。

下面是代码:

```c++

#include <iostream>
#include <list>
#include <algorithm>

void outint(int x) {std::cout << x << " ";}
int main()
{
        using std::list;
        using std::cout;
        using std::endl;
        int a[6] = {12, 8, 90, 105, 33, 459};
        list<int> list_1(a, a+ 6);
        for_each(a, a + 6, outint);
        cout << '\n';
        return 0;
}



```

  • 写回答

4条回答 默认 最新

  • [PE]经典八炮 2023-09-09 14:09
    关注

    上面的代码,是你亲自试过可以编译通过的吗

    本回答被专家选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 10月6日
  • 专家已采纳回答 9月28日
  • 创建了问题 9月9日

悬赏问题

  • ¥20 帮我解决这个项目,thank you各位程序员
  • ¥15 哪位能用ea软件做一下,有偿
  • ¥15 按要求编写汇编语言,并设计仿真电路图
  • ¥15 电脑软件运行次数如何统计
  • ¥15 同一个浏览器打开两个窗口怎么区分会话
  • ¥100 如何编写自己的emmc镜像
  • ¥15 starccm线性内聚力模型
  • ¥15 点云四边形凸包确定顶点
  • ¥15 关于redhat虚拟机系统新建卷的问题
  • ¥50 WRFDA读取风云四号A 星的GIIRS数据