有一种方法可以执行以下操作,但是只将bounds
传递给printf
吗?
double *bounds = getBounds();
printf("%f-%f, %f-%f, %f-%f",
bounds[0], bounds[1],
bounds[2], bounds[3],
bounds[4], bounds[5] );
// what I'd like to write instead:
xxxprintf("%f-%f, %f-%f, %f-%f", bounds);
最佳答案
我认为您要优化此设置的原因是,您需要在程序中打印很多边界,并且这样编写很麻烦,容易出错等。
在C语言中,您可以使用如下宏:
#define BOUNDS_FORMAT "%f-%f, %f-%f, %f-%f"
#define BOUNDS_ARG(b) b[0], b[1], b[2], b[3], b[4], b[5]
然后像这样写:
printf(BOUNDS_FORMAT, BOUNDS_ARG(bounds));
// ... some other code, then another call, with more text around this time:
printf("Output of pass #%d: " BOUNDS_FORMAT "\n", passNumber, BOUNDS_ARG(bounds));
在C++中,更期望您使用
std::cout
或类似的流。然后,您可以编写一个自定义对象来为您执行此操作:class PrintBounds {
protected:
const double* m_bounds;
public:
PrintBounds(const double* bounds)
: m_bounds(bounds)
{
}
friend std::ostream& operator<<(std::ostream& os, const PrintBounds& self)
{
os << self.m_bounds[0] << "-" << self.m_bounds[1] << ", "
<< self.m_bounds[2] << "-" << self.m_bounds[3] << ", "
<< self.m_bounds[3] << "-" << self.m_bounds[5];
return os;
}
};
然后,您将像这样使用它:
std::cout << "Some other text: " << PrintBounds(bounds) << " ...\n";
关于c++ - 将数组作为参数传递给printf,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23564715/