how to do that, one problem in Template. help!!!

L

Lordaeron

class Data1
{
int i;
char c[4];
}
class Data2
{
int i;
char d[5];
double dd;
}
template <typename T> class TableObject
{
public:
list<T*> links;
typename list<T*>::iterator ite;
TableObject(){
//do insert Data1 or Data2 into links
}
~TableObject(){}
Sort(){
ite=links.begin();
int i=0;
while ((ite+i)<links.end()){
if (*(ite+i).i>*(ite+i+1).i){//<-it seems impossible work
iter_swap((ite+i),(ite+i+1))
}
i++;
}
}

at the mark "<-"
how can i make it work like that?
can in template, so the Type is unknow at compile time.
so i can't do that?
 
K

Klaus Eichner

Lordaeron said:
class Data1
{
int i;
char c[4];
}
class Data2
{
int i;
char d[5];
double dd;
}
template <typename T> class TableObject
{
public:
list<T*> links;
typename list<T*>::iterator ite;
TableObject(){
//do insert Data1 or Data2 into links
}
~TableObject(){}
Sort(){
ite=links.begin();
int i=0;
while ((ite+i)<links.end()){
if (*(ite+i).i>*(ite+i+1).i){//<-it seems impossible work

That's probably because std::list::iterators are not random-access, but
bi-directional, i.e. you are not allowed say 'ite+1' (or 'ite-1'), but you
can say 'ite++ (or 'ite--'). You could either use the std::list::sort()
function or you swap std::list with std::vector.
 
J

John Harrison

Lordaeron said:
class Data1
{
int i;
char c[4];
}
class Data2
{
int i;
char d[5];
double dd;
}
template <typename T> class TableObject
{
public:
list<T*> links;
typename list<T*>::iterator ite;
TableObject(){
//do insert Data1 or Data2 into links
}
~TableObject(){}
Sort(){
ite=links.begin();
int i=0;
while ((ite+i)<links.end()){
if (*(ite+i).i>*(ite+i+1).i){//<-it seems impossible work
iter_swap((ite+i),(ite+i+1))
}
i++;
}

Sort()
{
typename list<T*>::iterator i = links.begin();
if (i == links.end())
return;
typename list<T*>::iterator j = i;
while (++j != links.end())
{
if (i->i > j->i)
iter_swap(i, j);
i = j;
}
}

I think you need to remove ite from your class, looks like you are using
member variables when you should be using local variables.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,113
Messages
2,570,690
Members
47,269
Latest member
VitoYwo03

Latest Threads

Top