gpt4 book ai didi

c++ - 函数返回如何返回特定计数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:45:05 25 4
gpt4 key购买 nike

下面是一个计算网格中每个字符的函数。我想让这个函数返回每个字符的计数,但我被卡住了。请问如何改进下面的函数,以便我可以返回处理其他方法所需的每个计数。

int getNeighborhood(const char** grid, int N, int row, int col, int& bCount, int& fCount, int& rCount, int& gCount){
int currRow;
int currCol;
int countB = 0;
int countF = 0;
int countR = 0;
int countG = 0;

//loop through all 8 grids surrounding the current row and column.
for(int i = -1; i < 2; i++)
{
for(int j = -1; j < 2; j++){
currRow = row + i; //current row.
currCol = col + i; //current column.

if(currRow >= 0 && currRow < N && currCol >= 0 && currCol < N){
if(grid[row][col] == 'B')
{
++countB;
}
if(grid[row][col] == 'F')
{
++countF;
}
if(grid[row][col] == 'R')
{
++countR;
}
if(grid[row][col] == 'G')
{
++countG;
}
}
}
//return statement required
}

最佳答案

也许你可以使用 std::map

std::map<char,int> getNeighborhood(const char** grid, int N, int row, int col){
int currRow;
int currCol;
//contain all character to count
std::string chElementToCount = "BFGR";

//The frequency is a map <char,int> correspond to <character to count, frequency>
std::map<char, int> frequency;

// intialize all frequency by 0
for (auto& ch: chElementToCount) {
frequency.insert(std::make_pair(ch,0));
}
for(int i = -1; i < 2; i++)
{
for(int j = -1; j < 2; j++){
currRow = row + i; //current row.
currCol = col + i; //current column.

// just get value of current char for easier later access
auto ch = grid[row][col];

if(currRow >= 0 && currRow < N && currCol >= 0 && currCol < N){

// the current char is a desired-to-count character then increase it frequency
if (chElementToCount.find(ch) != std::string::npos)
frequency[ch]++;
}
}
}
return frequency;
}

这是一个使用 std::map http://www.cplusplus.com/reference/map/map/map/ 的例子

关于c++ - 函数返回如何返回特定计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40394661/

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