这错哪了,急死人了。
#include <iostream>
#include <vector>
#include <algorithm>
template <int theValue>
void add (int& elem)
{
elem += theValue;
}
template <class T>
inline void PRINT_ELEMENTS (const T& coll, const char* optcstr = " ")
{
typename T::const_iterator pos;
std::cout << optcstr;
for (pos = coll.begin(); pos != coll.end(); ++pos)
std::cout << *pos << ' ';
std::cout << std::endl;
}
int main()
{
std::vector <int> coll;
std::for_each (coll.begin(),coll.end(),add<10>);
PRINT_ELEMENTS (coll);
return 0;
}
问题点数:20、回复次数:7Top
1 楼kingfox(小狐仙)回复于 2004-08-01 21:37:18 得分 0
coll初始化时没有任何元素,所以什么都打印不出来。
coll的定义应该这样:std::vector <int> coll(10);
这样就会打印10个元素。
Top
2 楼RookieStar(Yukon)回复于 2004-08-01 22:04:06 得分 10
楼上的说得对。
std::vector <int> coll;
std::for_each (coll.begin(),coll.end(),add<10>); // 这里的coll.begin()和coll.end()指的是同一个元素,所以for_each根本就没调用add<10>这个函数对象,自然什么都不会加了。
解决方法:std::vector <int> coll(10);
Top
3 楼kaphoon(齐柏林飞艇)回复于 2004-08-01 22:10:42 得分 10
std::for_each (coll.begin(),coll.end(),add<10>);
也有问题,它要得是函数对象,所以应该用ptr_fun把它转变为函数对象~
Top
4 楼kaphoon(齐柏林飞艇)回复于 2004-08-01 22:28:36 得分 0
我搞错了ptr_fun不要也没有关系~Top
5 楼steel007(小宝)(工作在windows和linux平台上)回复于 2004-08-01 23:05:38 得分 0
楼主用的什么编译器,偶用DEV-C++4.9.8.9,没有任何问题啊Top
6 楼Mars8888(ming)回复于 2004-08-03 08:07:12 得分 0
我改成了std::vector <int> coll(10);
在vc6.0下有两个错误:
ming1.obj : error LNK2001: unresolved external symbol "void __cdecl add(int &)" (?add@@YAXAAH@Z)
Debug/ming1.exe : fatal error LNK1120: 1 unresolved externals
用DEV-C++4.9但输出不了啊。Top
7 楼RookieStar(Yukon)回复于 2004-08-03 10:16:07 得分 0
VC6对模板支持得不好,VC7.1,DEV-C++都没问题。
输出不了?在return 0;前加一句system("pause");试试。Top




