最近在百度知道上回答了一道问题,并为他封装了一个类来解决。大意是不开辟新的数组同时排序两个数组。
http://zhidao.baidu.com/question/112777967.html
之后想要给这个类添加iterator好直接使用sort之类的函数,经过1个多小时的忙碌(能力有限,可以鄙视一下),终于实现了random_access_iterator。
上源码:
template<typename T>
class Obj;
template<typename T>
class Obj_iterator : public std::iterator <std::random_access_iterator_tag , T>
{
public:
Obj_iterator() : m_Obj(NULL) , m_index(0) {}
Obj_iterator( Obj<T> *p , size_t index ) : m_Obj(p) , m_index(index){}
Obj_iterator& operator = ( const Obj_iterator &t )
{
m_index = t.m_index;
m_Obj = t.m_Obj;
return *this;
}
bool operator ==( const Obj_iterator &rh ) const
{
return rh.m_Obj == m_Obj && rh.m_index == m_index;
}
bool operator !=( const Obj_iterator &rh ) const
{
return !( *this == rh );
}
Obj_iterator operator ++()
{
++m_index;
return Obj_iterator(m_Obj,m_index);
}
Obj_iterator operator ++( int )
{
Obj_iterator x = *this;
++(*this);
return x;
}
Obj_iterator operator -- ()
{
--m_index;
return Obj_iterator(m_Obj , m_index);
}
//一开始这里总是过不去,后来回想起以前遇到的问题,才知道需要在后面加上const来修饰,原因如下
/*
C++不鼓励把非常量引用绑定到临时对象
非const的operator*有可能改变对象值,从而对象整体的const性质得不到保证
*/
T& operator *() const
{
return (*m_Obj)[m_index];
}
T* operator ->() const
{
return &(*m_Obj[m_index]);
}
const Obj_iterator operator +(size_t n)
{
return Obj_iterator(m_Obj , m_index + n);
}
const Obj_iterator operator += (size_t n)
{
m_index += n;
return *this;
}
difference_type operator -(const Obj_iterator &n)
{
return m_index - n.m_index;
}
Obj_iterator operator -(size_t n)
{
return Obj_iterator(m_Obj , m_index-n);
}
bool operator < (const Obj_iterator n) const
{
return m_index<n.m_index;
}
protected:
private:
Obj<T> *m_Obj;
size_t m_index;
};
template <typename T>
class Obj
{
public:
Obj(T *p1,size_t sizeofp1,T *p2,size_t sizeofp2):
m_p1(p1),
m_p2(p2),
m_sizeofp1(sizeofp1),
m_sizeofp2(sizeofp2)
{
m_sumsize = sizeofp1+sizeofp2;
}
typedef Obj_iterator<T> iterator;
T& operator [](size_t index)
{
if (index > m_sizeofp1 + m_sizeofp2)
{
throw std::out_of_range("out_of_range");
}
if (index<m_sizeofp1)
{
return m_p1[index];
}
else
{
return m_p2[index - m_sizeofp1];
}
}
size_t size() const
{
return m_sumsize;
}
iterator begin()
{
return iterator(this,0);
}
iterator end()
{
return iterator(this,m_sumsize);
}
protected:
private:
T *m_p1;
T *m_p2;
size_t m_sizeofp1;
size_t m_sizeofp2;
size_t m_sumsize;
};
int _tmain(int argc, _TCHAR* argv[])
{
int p1[] = {1,6,3,123456,2,67,2,8};
int p2[] = {4,2,6,234,9,4,0,5};
Obj<int> h(p1 , sizeof(p1)/sizeof(*p1) , p2 , sizeof(p2)/sizeof(*p2));
std::copy(h.begin() , h.end() , std::ostream_iterator<int>(std::cout," "));
std::cout<<std::endl;
std::sort(h.begin() , h.end());
std::copy(h.begin() , h.end(),std::ostream_iterator<int>(std::cout,"\n"));
return EXIT_SUCCESS;
}
这段程序在我的vs2008上正确编译执行。
posted on 2009-08-20 10:06
HIT@ME 阅读(1864)
评论(4) 编辑 收藏 引用