c++ - 检查二维数组中是否存在元素 C++

标签 c++ arrays sorting

我正在尝试检查字符元素是否在我的输出数组中。该数组正在获取字符串中字符的频率。所以我想说,如果当前字符在数组中,则将频率加 1,否则将字符添加到数组中,频率为 1。另外,我希望表格按顺序显示前 5 个最高频率。

表格应该是什么样子的 EX:

  character: a b c d
  freqency:  1 2 3 4


string input = GetInputString(inputFileName);
char ** output; 

for (int i = 0; i < sizeof(output); i++)
{
      if (input [count] == output[i][]) // this is where my issue is
      {

            //.......
      }

}

最佳答案

您可以使用 std::vector<std::pair<char,int>> 来存储字符及其计数。

string input("1212345678999");

std::vector<std::pair<char, int>> sp;
for(auto c : input)
{
  auto it = std::find_if(sp.begin(), sp.end(), 
                         [=](const pair<int, char>& p) {return p.first == c; });
  if (it != sp.end())
  {
    it->second++;  // if char is found, increase count
  }
  else
  {
    sp.push_back(std::make_pair(c, 1)); // new char, add an entry and initialize count to 1
  }
}

要按顺序显示前 5 个最高频率,您可以按 count 以合适的顺序排序:

std::sort(sp.begin(), sp.end(), 
                      [](const pair<int, char>& p1, const pair<int, char>& p2)
                      {
                         return p1.second > p2.second; 
                      });

关于c++ - 检查二维数组中是否存在元素 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19217363/

相关文章:

c++ - 如何防止窗口被停用?

C++当您取消引用指向类对象的指针然后将其作为引用返回时,您可以在此引用上调用方法吗

c++ - 为什么代码以线性方式比以循环方式运行得慢?

javascript - 如果索引大于 arr 长度,它应该再次返回

php - 遍历php多级关联数组

php - MySQL : random sort than sort by a specific column

android - 如何在 flutter 中按字母顺序对外部存储中的歌曲列表进行排序

c++ - 指定哈希函数时在 unordered_map<> 中使用默认桶计数

jquery - 解析数组中的JSON数组并使用键值

python - 棘手的 Python 数组排序