添加初始值设定项列表的元素
Add the elements of an initializer list
>我正在尝试编写一个通用函数,该函数将初始值设定项列表作为参数,添加元素,然后返回该数字。如果列表为空,则它应返回 0。代码对我来说看起来是正确的,但是每当我运行它时,它都会从 {1, 2, 3, 4} 输入中返回 4,199,041 而不是 10。我更改了打印元素的功能,而不是添加它们,效果很好,它输出 1234,所以我不知道问题是什么。任何帮助将不胜感激。
#include <iostream>
#include <initializer_list>
template <typename T>
//add elements of initializer list
T total(initializer_list<T> & elements)
{
T tmp;
if(elements.size() != 0)
{
for(auto itr = elements.begin(); itr != elements.end(); ++itr)
{
tmp += *itr;
return tmp;
}
}else
return 0;
}
int main()
{
initializer_list<int> num({1, 2, 3, 4});
cout << total(num);
return 0;
}
你可以考虑 std::accumulate:
#include <algorithm>
#include <iostream>
#include <initializer_list>
template <typename T>
//add elements of initializer list
T total(std::initializer_list<T> & elements)
{
// Note: Using 0 will decay the result to an integer, hence the T{} for zero.
return std::accumulate(elements.begin(), elements.end(), T{});
// Fixing the original code (where tmp is uninitialized
// and the return tmp; is misplaced):
// T tmp = 0;
// for(auto itr = elements.begin(); itr != elements.end(); ++itr)
// tmp += *itr;
// return tmp;
}
int main()
{
std::initializer_list<int> num({1, 2, 3, 4});
std::cout << total(num) << 'n';
}
相关文章:
- C++如何通过用户输入删除列表元素
- 通过动态分配插入列表元素
- 用于编织链接列表元素的Runner Technique
- 无法在C 中删除列表元素
- 如何在不使用循环或迭代器的情况下检查所有列表元素并在满足条件时删除一个
- 将列表元素移动到列表末尾的函数多次不起作用
- 交换链接列表元素
- 当删除列表元素时,在迭代器结束时会发生什么
- 为什么从不同分配器的列表中剪辑列表元素时会有错误消息?以及如何解决
- 打印出列表元素问题
- 我想通过递归获取列表元素的所有置换
- 从C++访问列表元素 (QML) 颜色
- 如何在C++visual studio 2013中将列表元素转换为文本块
- 指向删除后的列表元素的指针
- 正在将指针复制到assign运算符中的另一个列表元素
- 将列表元素插入向量,C++获取其他不需要的值
- 从unordered_set中删除列表元素
- 在C++中打印列表元素的组件
- 提取并转换 boost::p ython::list 的列表元素
- Rcpp犰狳:对列表元素的"-="操作