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

标签 c++ arrays c++11 for-loop methods

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

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/

相关文章:

c++ - 在 C++11 foreach 循环中获取索引

c++ - 在 "no default constructor"的构造函数的第一个括号中获取 C2512 `ClassA` for `ClassB` 错误?

javascript - 为什么我的 8 拼图解决方案在我创建两次数组时运行得更快

c++11 - 比较 shared_ptr 实例的有效情况

c++ - 编译器用来决定 move 操作是否安全的标准是什么?

javascript - 如何检查一个字符串是否包含 JavaScript 中预定义数组中存在的子字符串?

c++ - 用 g++ 编译包含 cppunit 的程序

c++ - 具有不同参数的继承类构造函数的术语是什么?

c++ - 使用带有 std::shared_ptr 的 Qt 对象

python - 数组不会在 python 中分配超过 8 个字符