[英]Summation of a list of pointers
我被指针数组迷住了..如果我有一个这样定义的列表:
std::list<float*> total;
谁能让我知道如何相互添加元素?
for(int i = 0; i < total.size(); i++)
{
// add elements
}
它就像指针数组一样。 我不知道如何总结它们。 我是C ++编程的新手。
编辑:
感谢您的所有答复,但由于此指针指向Mat(opencv /图像处理),在我的情况下似乎不起作用:(
std::list<float*> total;
float sum = 0.0f;
for ( float *p : total ) sum += *p;
要么
for ( list<float *>::size_type i = 0; i < total.size(); i++ ) sum += *total[i];
要么
float sum = std::accumulate( total.begin(), total.end(), 0.0f,
[]( float acc, float *value ) { return ( acc += *value ); } );
编辑。 第二个示例无效。 列表中没有下标运算符。 所以我将其更改为以下内容
for ( auto it = total.begin(); it != total.end(); ++it ) sum += **it;
访问列表时,您需要使用*
运算符取消对指针的引用 ,如下所示:
*(total[i])
但是,将项目存储为std::list<float>
要容易得多-默认情况下,STL容器默认将其内容粘贴在堆上。
最好的方法是使用迭代器 :这样,如果您更改容器类型,则无需进行大量重构:
std::list<float*> total;
float sum = 0.0f;
for (std::list<float*>::const_iterator it = total.begin(); it != total.end(); ++it)
{
sum += **it;
}
请注意双重取消引用: *it
返回被容器 (在您的情况下为float*
),因此您需要再次取消引用以提取实际的float
。
如果您有一个std::list<float>
(会更正常),那么您可能会轻而易举地使用累加器 。
C ++ 11
C ++ 11添加了可以在此处利用的新功能。
1)重新定义auto
。 编译器将定义适当的类型。 你可以写
for (auto it = total.begin(); it != total.end(); ++it)
这大大减少了维护费用。
2)范围。 如果.begin()和.end()定义明确,则可以编写
for (auto it : total)
float sum = 0f;
for(float* element : list)
{
sum += *element; // for every element, add the value at the address pointed by the element.
}
std::list
表示一个(双链接)列表,因此您应该使用基于范围的for循环(如果使用c ++ 11支持进行编译)或迭代器来循环访问元素。
对于您来说,每个元素都是一个指向浮点数的指针/引用,因此要访问该值,您需要取消引用该指针。 这是基于范围的for循环构造的示例:
float sum = 0;
for (float* element : total) {
sum += *element;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.