Afficher un message
Vieux 18/10/2007, 09h22   #3
Kai-Uwe Bux
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: How to use the iterator from base class in a derived class?

wangxiaohu wrote:

> I am trying to write a class myVector based on std::vector and add
> only a sort method.


BadIdea(tm). That is abuse of inheritance. You should use a free standing
function instead:

template < typename T, typename A >
void sort_vector ( std::vector<T,A> & sequence ) {
std::sort( sequence.begin(), sequence.end() );
}

or maybe even more generic:

template < typename Container >
void sort_sequence ( Container & sequence ) {
std::sort( sequence.begin(), sequence.end() );
}

or with a concept check:

template < typename Container >
void sort_sequence
( Container & sequence,
typename enable_if
< is_sequence< Container >::value, void* >::type = 0 ) {
std::sort( sequence.begin(), sequence.end() );
}


There are some cases where public inheritance from std::vector<> is
justified. This does not look like one of them.


> The sort method needs to access the array stored
> in the base class using iterator. I have following draft code. However
> it never compile. Can anyone take a look and tell me how to fix it?
> Thanks!
>
> #include <vector>
> #include <iostream>
>
> using namespace std;


Don't put using directives in header files. Your decision to pull all
identifiers from the standard namespace is inflicted upon every user of
your class. That is very intrusive.


> template <typename T> class myVector : public vector<T>
> {
> public:
> void Sort();
> };
>
> template <typename T> void Sort<T>::Sort()


Shouldn't that be something like

template <typename T>
void myVector::Sort()


> {
> if (this.size() < 2)
> {
> return;
> }
>
> vector<T>::iterator i;


You would need to say

typename std::vector<T>::iterator i;

The keyword here is "dependent name".


>
> for (i = this.begin(); i != this.end(); i++)
> {
> //rest part ignored....
> }
> }


BTW: why are you doing your own sort algorithm? any why only for vectors? It
is _very_ hard to beat std::sort() from the header <algorithm>.


Best

Kai-Uwe Bux
  Réponse avec citation
 
Page generated in 0,05359 seconds with 9 queries