C++ C++;:从指向双精度数组的指针获取迭代器

C++ C++;:从指向双精度数组的指针获取迭代器,c++,pointers,iterator,C++,Pointers,Iterator,我有一个指向double的指针,我正在分配n个单元格。现在我需要访问这个指针的开始和结束迭代器对象。这是我的密码: *my_module.cpp* # include c_vector.h /* .. */ C_Vector a(n); *c_向量.h* class C_Vector{ /* .. */ public: C_Vector (int n); bool Create (int n); private: int n_s; double *z; } *c_vect

我有一个指向double的指针,我正在分配n个单元格。现在我需要访问这个指针的开始和结束迭代器对象。这是我的密码:

*my_module.cpp*

# include c_vector.h
/* .. */

C_Vector a(n);
*c_向量.h*

class C_Vector{

/* .. */
public:
  C_Vector (int n);
  bool Create (int n);
private:
  int n_s;
  double *z;
}
*c_vector.cpp*

C_Vector::C_Vector(int n) {
   Create(n);
}
bool C_Vector::Create(int n) {

   if ( (z = (double *)malloc(n * sizeof(double))) != NULL ){
        n_s = n;
   }
}
现在,在我的模块文件中,我希望访问a.begin()。 我该怎么做?可能吗? 请告知


Avishek

所以写
开始
结束
成员函数:

typedef double * iterator;
iterator begin() {return z;}
iterator end()   {return z + n_s;}
礼貌的做法是提供
const
重载:

typedef double const * const_iterator;
const_iterator begin()  const {return z;}
const_iterator end()    const {return z + n_s;}
const_iterator cbegin() const {return begin();}
const_iterator cend()   const {return end();}

然后,一旦你学会了如何实现一个向量,就使用
std::vector

对不起,我不建议在这里使用指针;更适合使用包含的、动态分配的数组,如
std::vector
。此外,原始指针没有
begin
end
方法:

class C_Vector
{
public:
    // ...
private:
    std::vector<double> z;
// ^^^^^^^^^^^^^^^^^^^^^^^
};
类C_向量 { 公众: // ... 私人: std::向量z; // ^^^^^^^^^^^^^^^^^^^^^^^ };
你是说
z.begin()
?你可以用*z来获取第一个元素,用*(z+n)来获取第n个元素否…我的“数组”是一个!@库纳尔:是的,你是对的,但我必须像迈克指出的那样定义我自己的开始和结束。“请建议。”不要使用
malloc
,也要使用
std::vector
。我需要一个迭代器对象来使用算法。@avishedutta:指针可以用作迭代器。我在做向量。但是你知道……老板!关于你之前的评论,我实际上是在谈论“算法”库,我想使用find()或max_element()@avishedutta:是的,你可以在
库中使用指针作为迭代器。迭代器不必是类类型;他们只需要支持各种操作,比如用
*
去引用,用
++
递增,等等,所有这些都是由指针支持的。@0x499602D2&Mike:感受我的痛苦吧!我使用的是开源代码库,所有类型都在那里定义,我必须使用它们的类型。