伸手,c++ primer 第四版课后习题 11.4
c++吧
全部回复
仅看楼主
level 10

题目:假定v是vector<double>类型的对象,则调用accumulate(v.begin(),v.end,0)是否有错?如果有的话,错在哪里?
我写代码跑了一下,果然报错,改成accumulate(v.begin(),v.end,0)就不报错了。求问为什么会报错,难道int自动转double都不让转了吗[拍砖]
代码如下:
#include <numeric>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<double> v;
for(int i=0;i<=10;i++)
v.push_back(i);
double y=accumulate(v.begin(),v.end(),0);
//报错,最后一个0改成0.0就不会报错了
cout<<y<<endl;
return 0;
}
2012年12月10日 14点12分 1
level 1
因为这个累加首先要知道类型才能分配内存空间,比如你装的是string类型,后面写个0肯定是不能累加的
2012年12月11日 00点12分 3
level 12
模板未实例化之前,需要精确的匹配
2012年12月11日 01点12分 5
[拜]多谢... 不过话说你怎么在“相亲”吧都十级了,给真程序员跪下了[拜]
2012年12月11日 07点12分
回复 挂羊头卖犬肉 : 以前在那吧里面水,那里欢乐多,[呵呵]有了贴吧签到功能,现在升级快多了,很多贴吧我都不看,只签到。
2012年12月11日 08点12分
回复 挂羊头卖犬肉 : 这个例子不是精确匹配的问题,只是明确实例化后的类型转换丢数据。
2012年12月11日 08点12分
level 10
没错,VS2012编译运行没问题。
顺便贴上accumulate的实现
template<class _InIt,
class _Ty> inline
_Ty _Accumulate(_InIt _First, _InIt _Last, _Ty _Val)
{
// return sum of _Val and all in [_First, _Last)
for (; _First != _Last; ++_First)
_Val = (_Ty)(_Val + *_First);
return (_Val);
}
2012年12月11日 05点12分 6
[拜]VS2008也没报错,我犯2了,不过看了大家的回复对这个理解又深了不少,也值得了,拜谢大神
2012年12月11日 07点12分
level 10
template<class _InIt,
class _Ty> inline
_Ty _Accumulate(_InIt _First, _InIt _Last, _Ty _Val)
{
// return sum of _Val and all in [_First, _Last)
for (; _First != _Last; ++_First)
_Val = (_Ty)(_Val + *_First);
return (_Val);
}
2012年12月11日 05点12分 7
擦,不贴了,你自己看吧
2012年12月11日 05点12分
回复 candy76041820 :格式[拍砖]
2012年12月11日 06点12分
回复 月无踪 :我在VS里面也是进入到这里的。“_Val = (_Ty)(_Val + *_First);”,这一句也就是 int =(int)(int + double),这个为什么会报错呢?
2012年12月11日 07点12分
回复 candy76041820 :上面的问题,orz求回答
2012年12月11日 07点12分
level 11
soga
2012年12月11日 06点12分 8
level 10
1>------ 已启动生成: 项目: 第十一章, 配置: Debug Win32 ------
1>正在编译...
1>test.cpp
1>c:\program files\microsoft visual studio 9.0\vc\include\numeric(25) : warning C4244: “=”: 从“double”转换到“int”,可能丢失数据
1> c:\program files\microsoft visual studio 9.0\vc\include\numeric(33): 参见对正在编译的函数 模板 实例化“_Ty std::_Accumulate<std::_Vector_iterator<double,_Alloc>,_Ty>(_InIt,_InIt,_Ty)”的引用
1> with
1> [
1> _Ty=int,
1> _Alloc=std::allocator<double>,
1> _InIt=std::_Vector_iterator<double,std::allocator<double>>
1> ]
1> g:\c++工程文件\c++primer_vs2008\第十一章\第十一章\test.cpp(13): 参见对正在编译的函数 模板 实例化“_Ty std::accumulate<std::_Vector_iterator<double,_Alloc>,int>(_InIt,_InIt,_Ty)”的引用
1> with
1> [
1> _Ty=int,
1> _Alloc=std::allocator<double>,
1> _InIt=std::_Vector_iterator<double,std::allocator<double>>
1> ]
1>生成日志保存在“file://g:\c++工程文件\C++primer_vs2008\第十一章\第十一章\Debug\BuildLog.htm”
1>第十一章 - 0 个错误,1 个警告
========== 生成: 成功 1 个,失败 0 个,最新 0 个,跳过 0 个 ==========
2012年12月11日 07点12分 10
1