gpt4 book ai didi

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

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

我正在尝试检查字符元素是否在我的输出数组中。该数组正在获取字符串中字符的频率。所以我想说,如果当前字符在数组中,则将频率加 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/

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