Pregunta

I came across a statement which I didn’t understand. Can anyone explain me please. It is a C++ program to sort data.

#define PRINT(DATA,N) for(int i=0; i<N; i++) { cout<<"["<<i<<"]"<<DATA[i]<<endl; } cout<<endl;

And also when I tried to rearrange the statement in the below format,I got compilation error!

#define PRINT(DATA,N)
for(int i=0; i<N; i++)
{
   cout<<"["<<i<<"]"<<DATA[i]<<endl;
}
cout<<endl;
¿Fue útil?

Solución 2

It can be used if you properly define it. But .... just because it can be used, does not mean that it should be used.

Use std::copy_n:

std::copy_n(data, n, std::stream_iterator<X>(std::cout, " "));

That will print all the n items from data to the stdout, each separated by a space. Note that in the above code, X is the type of data[i].

Or write a proper function (not macro) to print in your own defined format. Preferably a function template with begin and end as function parameters. Have a look at how algorithms from the Standard library work and are implemented. That will help you to come up with a good generic design of your code. Explore and experiment with the library generic functions!

Otros consejos

  1. It's a macro, each time you write PRINT(DATA,N) the pre-processor will substitute it for the entire for loop, including the variables.
  2. You're missing \ signs at the end of each line. This tells it the Macro continues to the next line. (Look at Multi-statement Macros in C++
  3. If you use macro, use brackets around any variables (DATA) and (N). The substitution is literal and this will allow usages like PRINT(data, x+1) which otherwise cause unexpected results.
  4. Don't use macro unless you REALLY must, there are many problems that can arise from this, it doesn't have a scope and so on. You can write an inline method or use std::copy_n like Nawaz proposed

This isn't something you want to use a macro for.

Write a template function that does the exact same thing:

template<typename T>
void PRINT(const T &data, size_t n){
    for (size_t i=0;i<n;++i)
        cout << "["<<i<<"]"<<data[i]<<endl;
}

You should really avoid using macros. The only reason I find you NEED macros is when you need to use the name of the input (as string), or location (LINE or FILE) e.g.:

#define OUT(x) #x<<"="<<x<<"; "
#define DEB std::cerr<<"In "<<__FILE__<<":"<<__LINE__<<": "

for use in printing like this:

DEB << OUT(i)<<OUT(val[i])<<OUT(some_func(val[i],3))<<endl;

Which will print

In file.cc:153: i=4; val[i]=10; some_func(val[i],3)=4.32; 

This is a functionality you can't do without macros. Anything you CAN do without macros you SHOULD

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top