[英]Inheriting std::vector::iterator for custom class?
我正在實現一個包含STL std::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;
}
您不需要從迭代器本身繼承。 您可以只為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;
}
您可以為其創建公共代理功能
vector<T>::begin()
vector<T>::end()
vector<T>::cbegin()
vector<T>::cend()
然后迭代你的對象:
Custom custom;
// here insert any data
for(auto it = custom.cbegin(); it != custom.cend(); ++it){
cout << *it;
}
此外,它適用於基於范圍的:
for(const auto &val : custom){
cout << val;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.