在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;
}
```