c++中的指针和自递增参数
Pointers and self incrementing arguments in c++
请记住,我是指针的新手。
我试图实现的是,每次迭代for循环时,value
都会增加一个双倍的值(在本例中为.013):
/***********************************************************************************
@name: fill_array
@purpose: fill all elements in range 'begin' to 'end' with 'value'
@param: double* begin address of first element of the array range
@param: double* end address of the next byte past the end of the array range
@param: double value the value to store in each element
@return: void
***********************************************************************************/
void fill_array(double* begin, double* end, double value) {
for( ; begin < end; begin++)
*begin = value == 0.0 ? 0.0 : value;
}
一个不起作用的驱动程序代码示例(我提供这个只是为了更好地传达我想要实现的目标):
double dataValue = 3.54;
double* currentData = &dataValue;
fill_array(begin, end, *currentData+.013);
当然,存储在数组中的所有值都是3.553。
我是否需要创建一个带有返回值的函数,作为参数传递到形式参数"value"中?或者这可以只用指针来完成吗?
只需在每次迭代中增加值:
for( ; begin < end; begin++) {
*begin = value == 0.0 ? 0.0 : value;
value += 0.013;
}
如果您不希望0.013是一个动态的,那么您应该在函数中添加另一个参数(例如double incrementer
)。
每次遍历for循环时,值都会增加一个双倍值(在本例中为.013):
value
是调用者提供的函数参数,所以调用者可以这样修改:
fill_array(begin, end, *currentData += .013);
如果您不希望调用代码修改值,那么您必须进行一些其他更改,因为给定。。。
fill_array(begin, end, *currentData+.013);
为value
参数提供了添加的临时结果,并且没有fill_array
可以要求控制的非临时变量,以便它可以添加到其中并查看对下一次调用的影响。这可以通过几种方法来解决,使用指针。。。
void fill_array(double* begin, double* end, double* p_value) {
for( ; begin < end; begin++)
*begin = *p_value;
*p_value += 0.13;
}
fill_array(begin, end, currentData);
或使用引用。。。
void fill_array(double* begin, double* end, double& value) {
for( ; begin < end; begin++)
*begin = value;
value += 0.13;
}
fill_array(begin, end, *currentData);
不能使用函数fill_array来完成任务。但是你可以专门为这项任务超载。例如
void fill_array( double *begin, double *end, double init, double incr )
{
init = init == 0.0 ? 0.0 : init;
if ( begin != end )
{
*begin = init;
while ( ++begin != end ) *begin = init += incr;
}
}
或者,如果您将最后一个参数定义为具有默认参数,则您甚至只能拥有一个函数。例如
void fill_array( double *begin, double *end, double init, double incr = 0.0 )
{
init = init == 0.0 ? 0.0 : init;
if ( begin != end )
{
*begin = init;
while ( ++begin != end ) *begin = init += incr;
}
}
因此,如果你把它称为
fill_array( begin, end, 3.54 );
它将按照您原来的功能运行。
如果你称之为
fill_array( begin, end, 3.54, 0.13 );
它会表现出你想要达到的效果。
相关文章:
- 使用指向成员的指针将成员函数作为参数传递
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 修改函数中的指针(将另一个指针作为参数传递)
- Clang bug?使用指针作为模板参数
- MSVC将仅移动结构参数解释为指针
- 非类型指针和引用模板参数,以及在编译时如何/为什么解析它们.c++
- 如何使用非类型模板参数传入指向数组的指针
- 将成员函数指针作为参数传递给模板方法
- 匹配函数指针作为模板参数?
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 通过智能指针和转换对基本模板参数进行模板推导
- 为函数定义符号不明确的指针参数
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- C++ - 声明指向返回任何类型并获取任意数量参数的函数的指针
- 将函数参数完美转发到函数指针:按值传递呢?
- 保留函数指针模板参数
- 如何构造一个以可变参数指针函数作为成员的类?
- 指向对象的非类型模板参数指针
- c++ 使用 *& as 参数(指针乐趣,三级树方法)