【发布时间】:2015-09-01 05:50:17
【问题描述】:
我刚刚阅读了有关模板和迭代器的一章,但这仍然很难理解。基本上我想创建一个 Set 模板类,它只接受你放入其中的每种类型的对象中的一种,使用向量实现。
问题是,我不知道Set类中的insert函数怎么写,嵌套迭代器类中的构造函数怎么写。另外,我提供的大部分功能都是文中章节中的示例,我什至不知道它们是否必要或者我做得对。注释?因为这是一个非常混乱的问题。这是我的代码:
//testSetClass.cpp
#include <iostream>
#include <vector>
using namespace std;
/****************************CLASS DEFINITION*********************************/
// -----------------------------------------
// SET
// -----------------------------------------
template <class T>
class Set
{
vector<T> theSet;
public:
Set() {}
Set(const Set& s): theSet(s.theSet){} //copy constructor
~Set(){ theSet.clear(); }
void insert(T t)
{
//insert in orderly fashion? as set class does too
//also, how do i check for duplicates?
theSet.push_back(t);
}
//nested iterator class: that supports the begin() and end() sentinel
class iterator; //declaration
friend class iterator;
class iterator //definition
{
Set<T>& s;
int index;
public:
iterator(const Set<T>& ss): s(ss), index(0){}
//to create the "end sentinel" operator:
iterator(Set<T>& ss,bool):s(ss){} //???
T operator*() {return s.theSet.at(index);} //is this right?
T operator++() //prefix form
{
return ++s.theSet.at(index);
}
T operator++(int) //postfix form
{
return s.theSet.at(index)++;
}
bool operator!=(const iterator& ri)const {return index!=ri.index;}
};
//iterators begin() and end()
iterator begin()const { return iterator (*this); }
//create the end sentinel:
iterator end() { return iterator (*this,true); } //why?
};
/*************************************END OF CLASS DEFINITIONS*********************************/
/* *****************************************************************************
* MAIN
* *****************************************************************************
*
* REMARKS:
* to test that the class works correctly.
* *****************************************************************************/
int main (int argv, char const *argc[])
{
Set<int> other;
for(int i = 0; i<10; ++i)
other.insert(i);
for(Set<int>::iterator start = other.begin(); start != other.end(); start++)
cout<<*start<<endl;
cout << "\n\nProgram ends successfully!" <<endl;
}
【问题讨论】:
-
您是否尝试使用 std::vector 来实现 std::set 规范作为教育练习?
-
一旦你完成它,你可以从代码审查codereview.stackexchange.com的人们那里得到很好的反馈
标签: c++ templates generics iterator set