print an array by C++

S

sofin

I have a 2-dimension array whose format can be either float or
integer.
I would like to write a function to print out this array no matter its
format is float or integer.
I don't know how to pass the argument because the format of the array
could be float or int?

void function(float array, row, col){
^^^^^^
Could be also int
int i=0;
int j=0;

for(j=0;j<col;j++){
for(i=0;i<row;i++){
cout << array[j] << endl;
}
}
}
 
C

ctrucza

I have a 2-dimension array whose format can be either float or
integer.
I would like to write a function to print out this array no matter its
format is float or integer.

First off: you should post compilable code.

You should write a function template:

template<class T>
void foo(T* a, int row, int col)
{
for(int j=0;j<col;j++)
{
for(int i=0;i<row;i++)
{
cout << a[i*col+j] << endl;
}
}
}

int main()
{
float f[4] = {0.1f,0.2f,0.3f,0.4f};
int n[4] = {42, 43, 44, 45};

foo<int>(n,2,2);
foo<float>(f,2,2);
}

I don't know how to pass the argument because the format of the array
could be float or int?

void function(float array, row, col){
                 ^^^^^^
                  Could be also int
int i=0;
int j=0;

   for(j=0;j<col;j++){
       for(i=0;i<row;i++){
             cout << array[j] << endl;
       }
   }

}
 
S

sofin

If I put foo function in foo.c and use main.c to call foo, when g++ -0
main.o foo.o ===>
it appears that "undefined reference to foo".
I test if foo is a normal function without template<class >, there is
no such a problem.
Can someone tell me why?
Thanks.




First off: you should post compilable code.
You should write a function template:
template<class T>
void foo(T* a, int row, int col)

The OP's array is apparently two-dimensional. It might be better to use
that in the declaration:


And then you have N and M for the counters to run up to, instead of
passing the arguments, which can easily be wrong.


for(int j=0;j<col;j++)
{
for(int i=0;i<row;i++)
{
cout << a[i*col+j] << endl;
}
}
}
int main()
{
float f[4] = {0.1f,0.2f,0.3f,0.4f};
int n[4] = {42, 43, 44, 45};
foo<int>(n,2,2);
foo<float>(f,2,2);
}

I don't know how to pass the argument because the format of the array
could be float or int?
void function(float array, row, col){
^^^^^^
Could be also int
int i=0;
int j=0;
for(j=0;j<col;j++){
for(i=0;i<row;i++){
cout << array[j] << endl;
}
}
}


V
 

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

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top