gpt4 book ai didi

c++ - 返回指向常量二维数组的指针的函数 (C++)

转载 作者:行者123 更新时间:2023-11-30 02:11:40 26 4
gpt4 key购买 nike

我是一个断断续续的程序员,最近似乎忘记了很多基础知识。

我创建了一个类 SimPars 来保存几个二维数组;下面显示的是 demPMFs。我要将指向 SimPars 实例的指针传递给其他类,我希望这些类能够使用 SimPars 访问器函数读取数组。速度和内存力很重要。

我知道使用 vector 通常会更简单,但在这种情况下,我真的很想坚持使用数组。

如何为数组编写访问器函数?如果我对第 n 个数组索引感兴趣,我如何使用返回的指针访问它? (我应该为数组的特定索引编写一个单独的访问器函数吗?)下面肯定是错误的。

// SimPars.h
#ifndef SIMPARS_H
#define SIMPARS_H
#include "Parameters.h" // includes array size information

class SimPars {
public:
SimPars( void );
~SimPars( void );

const double [][ INIT_NUM_AGE_CATS ] get_demPMFs() const;

private:
double demPMFs[ NUM_SOCIODEM_FILES ][ INIT_NUM_AGE_CATS ];

};
#endif


// SimPars.cpp
SimPars::SimPars() {
demPMFs[ NUM_SOCIODEM_FILES ][ INIT_NUM_AGE_CATS ];
// ...code snipped--demPMFs gets initialized...
}

//...destructor snipped
const double [][ INIT_NUM_AGE_CATS ] SimPars::get_demPMFs( void ) const {
return demPMFs;
}

我将不胜感激对建议的解决方案进行某种解释。

最佳答案

基本上,您有三种选择:通过引用返回整个数组,通过指针返回第一行,或者通过指针返回整个数组。这是实现:

typedef double array_row[INIT_NUM_AGE_CATS];

typedef array_row array_t[NUM_SOCIODEM_FILES];

array_t demPMFs;

const array_t& return_array_by_reference() const
{
return demPMFs;
}

const array_row* return_first_row_by_pointer() const
{
return demPMFs;
}

const array_t* return_array_by_pointer() const
{
return &demPMFs;
}

这里是用例:

SimPars foo;

double a = foo.return_array_by_reference()[0][0];
double b = foo.return_first_row_by_pointer()[0][0];
double c = (*foo.return_array_by_pointer())[0][0];

How would I return just the nth row of the array?

同样,您有三个选择:

const array_row& return_nth_row_by_reference(size_t row) const
{
return demPMFs[row];
}

const double* return_first_element_of_nth_row_by_pointer(size_t row) const
{
return demPMFs[row];
}

const array_row* return_nth_row_by_pointer(size_t row) const
{
return demPMFs + row;
}

关于c++ - 返回指向常量二维数组的指针的函数 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3112933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com