jha*_*sen 5 c++ iterator stl vector c++11
我正在实现一个包含 STLstd::vector作为中央数据成员的自定义类。现在,我希望这个类提供一个迭代器,它只需要遍历这个向量,并且还可以与基于 C++11 范围的迭代一起使用。以某种方式继承迭代器是非常诱人的,std::vector::iterator因为它应该做完全相同的工作。这是可能的还是我需要实现一个完全自定义的迭代器?
class Custom {
private:
std::vector<double> _data;
public:
class iterator {
// Want this to provide an interface to iterate through _data
// ...
};
// ...
};
Custom C;
// Populate C with data ...
for (const auto& item : C) {
// This should print the elements within _data.
std::cout << item << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您不需要从迭代器本身继承。您只需为std::vector<double>.
这是一个快速片段:
#include <vector>
#include <iostream>
class Custom {
private:
std::vector<double> _data;
public:
explicit Custom(std::initializer_list<double> init) : _data(init) {}
using iterator = std::vector<double>::iterator;
using const_iterator = std::vector<double>::const_iterator;
iterator begin()
{
return _data.begin();
}
iterator end()
{
return _data.end();
}
const_iterator cbegin() const
{
return _data.cbegin();
}
const_iterator cend() const
{
return _data.cend();
}
};
int main()
{
Custom C({ 1.0,2.0,3.0,4.0,5.0 });
for (const auto &item : C)
{
std::cout << item << "\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2872 次 |
| 最近记录: |