开始,结束简单类的迭代器规范
begin, end specifications for iterators for simple class
我想在我的Foo类
上使用我的printContainer()。我的 printContainer 在基本的 stl::vector 上运行良好,如 main() 所示。我的 Foo 类的 begin() end() 成员函数似乎在 main() 中的循环范围内工作。
但是我不能在我的Foo类上调用我的printContainer()。错误就是错误:调用 'begin(
我做错了什么?
#include <vector>
#include <iostream>
template <typename Iter, typename Cont>
bool isLast(Iter iter, const Cont& cont) {
return (iter != cont.end()) && (next(iter) == cont.end());
}
template <typename T>
struct is_cont {
static const bool value = false;
};
template <typename T,typename Alloc>
struct is_cont<std::vector<T,Alloc> > {
static const bool value = true;
};
template <typename T, typename std::enable_if< !is_cont<typename T::value_type>::value>::type* = nullptr >
std::string printContainer(T const& container)
{
std::string str = "{";
for (auto it = std::begin(container); it != std::end(container); ++ it)
str += (isLast(it, container) ? std::to_string(*it) + "}" : str += std::to_string(*it) + ",");
return str;
}
template <typename T, typename std::enable_if< is_cont<typename T::value_type>::value>::type* = nullptr >
std::string printContainer(T const& container)
{
std::string str = "{";
for (auto it = std::begin(container); it != std::end(container); ++ it)
str += (isLast(it, container) ? printContainer(*it) + "}" : str += printContainer(*it) + ",");
return str;
}
template <class T, class cmp=std::greater<T>>
class Foo
{
private:
std::vector<T> data_;
public:
typedef typename std::vector<T>::value_type value_type;
Foo(size_t n, T val) : data_(n, val) {}
typename std::vector<T>::iterator begin(){ return data_.begin(); } // for printContainer
typename std::vector<T>::iterator end() { return data_.end(); } // for printContainer
};
int main()
{
std::vector<std::vector<float>> a(2,std::vector<float>(3,3));
std::cout << printContainer(a) << std::endl; // it works !
Foo<float> b(10,2);
for (auto it = std::begin(b); it != std::end(b); it ++)
std::cout << *it << " "; // it works !
// std::cout << printContainer(b) << std::endl; // but this does not work !
}
传递一个const
容器,因此您需要Foo::begin() const
和Foo::end() const
成员函数。
您必须在Foo
类中添加这些const
成员,这些成员又返回 const 迭代器:
typename std::vector<T>::const_iterator begin() const { return data_.cbegin(); } // for printContainer
typename std::vector<T>::const_iterator end() const { return data_.cend(); } // for printContainer
现场演示
相关文章:
- 具有迭代器和自定义步长的循环结束条件
- C++不能取消引用结束列表迭代器
- 如何将迭代器(包括结束和开始之前的迭代器)测试到列表或forward_list保持有效
- 为什么 std::variant 使用开始和结束迭代器进行编译?
- unordered_map在结束迭代器上插入
- 如何从函数中返回迭代器,包括结束案例
- 插入新元素时结束迭代器会获得更新
- 射击时从列表中删除外星人 - 找出循环;"表达式:无法递增结束列表迭代器"
- 当没有迭代器失效时,这是否包括结束迭代器?
- 如何创建从开始和结束迭代器的范围
- 当删除列表元素时,在迭代器结束时会发生什么
- 结束迭代器和分割故障
- 字符串文本的C++宏开始迭代器和结束迭代器
- 使用过去结束迭代器的 std::iter_swap 不好吗?
- 开始,结束简单类的迭代器规范
- 如何返回提升multi_index迭代器的开始和结束
- 使用模板<类输入迭代器>字符串(输入迭代器开始,输入迭代器结束)时出现奇怪的错误;
- 迭代器结束检查在“for”循环内递增后失败
- 哨兵和结束迭代器有什么区别?
- 具有移动结束()的前向迭代器