添加初始值设定项列表的元素

Add the elements of an initializer list

本文关键字:列表 元素 添加      更新时间:2023-10-16

>我正在尝试编写一个通用函数,该函数将初始值设定项列表作为参数,添加元素,然后返回该数字。如果列表为空,则它应返回 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';
}