2011-10-10 43 views
1

我想知道如何在C++中正确使用for和while循环中的指针。通常我使用C而不是C++编写。我这次使用C++ std库的唯一原因是我可以使用代码中其他数学函数所需的复数函数。编译时使用指针for conditional while/for循环会产生错误

作为赋值的一部分,我们给了下面的函数声明。我写的部分是在函数中注释的。

typedef std::complex<double> complex; 

// Evaluates a polynomial using Horner's approach. 
// Inputs: 
// [coeffs, coeffs_end) - polynomial coefficients, ordered by descending power 
// x - point of evaluation 
// Outputs: 
// p - value of polynomial at x 
// dp - value of polynomial derivative at x 
// ddp - value of polynomials second derivative at x 
// 
template<typename T> 
inline void poly_val(T const* coeffs, T const* coeffs_end, T x, T & p, T & dp, T & ddp) 
    { 
     //MY CODE HERE 
     int i = 0; 
     const T *pnt = coeffs; 
     while(pnt != coeffs_end){ 
        //Evaluate coefficients for descending powers 
      p += coeffs(i)*pow(x,((coeffs_end-1)-i)); 
      pnt++; 
      i++; 
     } 
} 

的功能不知道数组的长度,所以我猜为停止条件指针“coeffs_end”,它指向数组“coeffs”的最后一个值。我可以在这种条件下使用指针吗? (传统上,我会喂阵列到函数的长度,但我们不能修改声明)

如果我这样做,这样一来我一直在编译时得到一个错误(我不明白):

C2064:长期敌人不能评价服用1个参数

以下行的函数:

 p += coeffs(i)*pow(x,((coeffs_end-1)-i)); 
+1

你到底打算让'coeffs(ⅰ)'做什么? 'coeffs'不是一种功能,是吗? – jwodder

+2

你确定它是'敌人'而不是'coeffs'的错误吗?另外,它应该是'coeffs [i]'而不是'coeffs(i)'? – quasiverse

+0

是的,它的意思是coeffs [i]。对不起,使用matlab太多了...... – user986875

回答

2

coeffs(i)被调用约定到取一个整数参数的函数。但在你的情况下,它是一个指针。因此,您需要使用[]运算符来访问索引处的元素。

另外((coeffs_end-1)-i)解析为地址位置。您需要解除引用才能获取该位置的值。

+0

太棒了。我改变了,现在我得到了编译错误错误C2665:'std :: pow':8重载没有一个可以转换所有参数类型 – user986875

+2

@ user986875 - 正如我所说的,你需要'*((coeffs_end-1 )-i)'提供该位置的引用。注意之前的'*'运算符。 – Mahesh

+0

啊我现在明白了。谢谢。 – user986875

1

也许它会更可读的清洁器的方式写:

#include <cmath> 
#include <iterator> 

template<typename T> 
inline void poly_val(T const* coeffs, T const* coeffs_end, T x, T & p, T & dp, T & ddp) 
{ 
    const std::size_t nterms = std::distance(coeffs, coeffs_end); 
    for (std::size_t i = 0; i != nterms; ++i) 
    { 
    p += coeffs[i] * std::pow(x, nterms - 1 - i); 
    } 
} 

由于原始指针可以作为迭代器被处理,我们可以使用std::distance来确定的范围所界定的阵列的大小[first, last)


编辑:NOTE:事实上这是可以做到更简单:

for (const T * it = coeffs; it != coeffs_end; ++it) 
    { 
    p += *it * std::pow(x, std::distance(it, coeffs_end) - 1); 
    } 
+0

不错!这非常有用。不知道std :: distance。谢谢你的提示。 – user986875

+0

@ user986875:'distance'不是绝对必要的,因为你可以说'coeffs_end - coeffs',但它是一个很好的接触,因为它是非常自我描述的。 –

+0

@ user986875:我添加了另一个更简单的选择。 –