gpt4 book ai didi

c++ - 如何将 char 设置为函数?我对语法感到困惑... set max_freq(map frequency)

转载 作者:行者123 更新时间:2023-11-28 04:22:00 25 4
gpt4 key购买 nike

你好,当我设置 <char> (Function(map<char ,int>...) 时,我不知道 set 是如何工作的编辑:

//Set map
map<char, int> frequency;

其次:

map<char, int> count_chars(const string input) {
// Given a map
map<char, int> frequency;
// Populate it with the count of each character in the input
//for loop to populate plus count
for(int i = 0; i < size; i++){
frequency[input[i]]++;
}

return frequency;
}

第三:

//Find highest occurence of character
char max_freq(map<char, int> frequency) {
int key = 0;
for (pair<char, int> elements : frequency){
// highest = element.first;
if(key <= elements.second){
key = elements.second;
highest = elements.first;
}
}
return highest;
}

最后:

//I added set<char> s into the code below and it solved the syntax error. Any better solutions?
enter code here
// Below is what I wrote, I am supposed to find max occurrences of the character but I think I do not understand the syntax.
set<char> max_freq(map<char, int> frequency)
{
char high;
int key = 0;
for (pair<char, int> elements : frequency)
{
if (key <= elements.second)
{
key = elements.second;
high = elements.first;
frequency[high];
}
}
return frequency;
}

我一直收到这个错误:

Map.cpp:117:12: error: could not convert 'frequency' from 'std::map' to 'std::set' return frequency;

最佳答案

这是你的函数签名:

set<char> max_freq(map<char, int> frequency)

这个签名说的是:

"max_freq 是一个函数,它按值获取类型为 map<char, int> 的对象,并返回类型为 set<char> 的对象。"。

这意味着你返回的对象类型必须是set<char>或者它必须可以隐式转换为该类型。但是您返回的是 map<char, int> 类型的对象, 这是无效的。要么更改签名以满足您的需要,要么制作一个兼容类型的对象并将其返回。

关于c++ - 如何将 char 设置为函数?我对语法感到困惑... set <char> max_freq(map<char, int> frequency),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55256933/

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