在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;
}
```
又实验了一下,如果 for_each()里面用数组名来做迭代器,它会提示没有声明 for_each;
如果里面用list的begin() end() 迭代器,它就通过,不提示错误。
上面的代码,是你亲自试过可以编译通过的吗
std::for_each(a, a + 6, outint);
【以下回答由 GPT 生成】
问题解答:
在调用 for_each() 函数时不需要加上 "std::" 前缀,而调用 remove_if() 函数时需要加上 "std::" 前缀的原因是因为这两个函数属于不同的命名空间。
首先,让我们看一下代码的导入和命名空间的使用情况。在程序开头使用了如下几条 using
声明:
using std::list;
using std::cout;
using std::endl;
这些声明的作用是将 std::list
,std::cout
和 std::endl
引入到当前命名空间中,以方便直接使用这些标识符。
在调用 for_each() 函数和 remove_if() 函数时,它们分别位于 <algorithm>
头文件中,而 <algorithm>
头文件中的函数都位于 std
命名空间中。
因此,对于 for_each() 函数,由于我们在代码开头已经使用了 using std::cout;
,即引入了 std
命名空间,所以在调用 for_each() 函数时可以直接使用其函数名。
而对于 remove_if() 函数,由于我们在代码中未明确使用 using std::remove_if;
,即未引入 std
命名空间,所以在调用 remove_if() 函数时需要加上 "std::" 前缀。
简而言之,对于需要在调用函数时加上前缀的情况,是因为当前命名空间中未引入对应的函数或类名。而对于不需要加前缀的情况,则是因为当前命名空间中已经引入了对应的函数或类名。
希望以上解答对您有帮助,如有其他疑问,请随时追问。