我需要获得仅包含双精度的列表的总和。 出于某种原因,这不起作用,但是:
#include <type_traits>
#include <utility>
template< std::size_t index, typename type >
struct ref { type & value; };
template< std::size_t index, typename type >
type && get(ref< index, type > const & r)
{
return std::forward< type >(r.value);
}
template< typename F, typename ...types, std::size_t ...indices >
decltype(auto) apply_inverse(F & f, types &... values, std::index_sequence< indices... >)
{
struct : ref< indices, types >... {} refs{{values}...};
constexpr std::size_t top = sizeof...(indices) - 1;
return std::forward< F >(f)(get< top - indices >(refs)...);
}
template< typename F, typename ...types >
decltype(auto) apply_inverse(F && f, types &&... values)
{
return apply_inverse< F, types... >(f, values..., std::index_sequence_for< types... >{});
}
#include <iostream>
int main()
{
auto const print = [] (auto const &... value) -> std::ostream & { return (std::cout << ... << value); };
apply_inverse(print, 1, 2, 3) << std::endl;
}
答案 0 :(得分:2)
你应该修改你的循环如下。
double sum(DoubleList* list) {
double sum = 0;
for (DoubleNode *n = list->first; n != NULL; n = n->next) {
sum += n->value;
}
return sum;
}
上面的示例代码假定DoubleNode 具有一个名为next的属性,其类型为DoubleNode *,它将指针存储到下一个元素。
答案 1 :(得分:1)
您需要确保获得循环中的下一个元素。我猜测next
指针是n->next
:
for (DoubleNode *n = list->first; n != NULL; n = n->next) {
sum += n->value;
}
答案 2 :(得分:1)
更改
for (DoubleNode *n = list->first; n != NULL; n = next)
到
for (DoubleNode *n = list->first; n != NULL; n = n->next)