我的自定义迭代器有什么问题
What is wrong with my custom iterator
所以,我一直在试图弄清楚自定义迭代器是如何工作的,在投入了这么多时间但仍然不足之后,我决定问整个社区:我做错了什么?请帮忙,解释会很好,但如果是"次要",则没有必要。
作为一个附带问题,有谁知道让"显示为集合关联"在 MSVS 中的类图中工作的要求是什么? 它只是不适用于C ++吗?就其而言,甚至我的 bar2 也不是整数的集合。
这是我的代码,它应该编译,但显然我的迭代器坏了......
编辑:既然人们在问,问题是我实现的迭代器没有迭代酒吧
#include <vector>
#include <iostream>
using namespace std;
template<class T>
class Foo
{
public:
template<class T>
class FooIterator : std::iterator<std::forward_iterator_tag, T, ptrdiff_t, T*, T&>
{
public:
Foo<T>* arrayPtr;
int index, size;
FooIterator(Foo<T>* arrayPtr, int size, int index) : arrayPtr(arrayPtr), size(size), index(index) {}
T& operator*() {return *(arrayPtr->operator[](index));}
T* operator->() {return &(operator*());}
FooIterator &operator++(){++index; return *this;}
FooIterator operator++(int){FooIterator tmp(*this); ++(*this); return tmp;}
bool operator!=(const FooIterator &other) const {return other.index == index;}
};
T** ts;
int size;
int index;
typedef FooIterator<T> fooiterator;
fooiterator begin(){return fooiterator(this, size, 0);}
fooiterator end(){return fooiterator(this, size, size);}
~Foo();
void init(int size);
void insert(T* item);
T* operator[](int index);
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef int size_type;
typedef ptrdiff_t difference_type;
};
template<class T>
void Foo<T>::init(int size)
{
ts = new T*[size];
index = 0;
}
template<class T>
Foo<T>::~Foo()
{
for(int i = 0; i < index; i++)
delete ts[i];
delete ts;
}
template<class T>
void Foo<T>::insert(T* item)
{
ts[index++] = item;
}
template<class T>
T* Foo<T>::operator[](int index)
{
return ts[index];
}
struct Bar
{
public:
Foo<int> nums;
Bar()
{
nums.init(3);
int val = 1;
nums.insert(new int(1));
nums.insert(new int(2));
nums.insert(new int(3));
for each (int var in nums)
{
cout << var << endl;
}
}
};
struct Bar2
{
vector<int> nums;
Bar2()
{
nums.push_back(4);
nums.push_back(5);
nums.push_back(6);
for each (int var in nums)
{
cout << var << endl;
}
}
};
int main ()
{
Bar bar;
/*for (int i = 0; i < bar.nums.index; i++)
{
cout << *bar.nums[i] << endl;
}*/
Bar2 bar2;
cin.get();
return 0;
}
一个明显的问题是,operator!=
实际上是在测试平等性。
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了