如何将char设置为函数?我对语法感到困惑...设置<char> max_freq(map <char,int =“”>频率)

时间:2019-03-20 09:00:39

标签: c++

嗨,我不知道设置<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:错误:无法从“   'std :: map'到'std :: set'        返回频率;

3 个答案:

答案 0 :(得分:2)

这是您的功能签名:

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

此签名的意思是:

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

这意味着您返回的对象的类型必须为set<char>或必须隐式转换为该类型。但是您将返回map<char, int>类型的对象,该对象无效。更改签名以适合您的需求,或者制作兼容类型的对象并将其返回。

答案 1 :(得分:0)

您的函数出现的问题似乎是没有从import React from 'react'; import { Route, Redirect } from 'react-router-dom'; const PrivateRoute = ({ component: Component, ...rest }) => { const isAuth = localStorage.getItem('isLoggedIn'); return ( <Route {...rest} render={props => isAuth ? ( <Component {...props} {...rest} /> ) : ( <Redirect to={{ pathname: "/admin/login", state: { from: props.location } }} /> ) } /> ); } export default PrivateRoute; (即您返回的内容)到std::map<char, int>(即函数返回类型)的隐式转换。

如果您对计数感兴趣,可以使用以下利用std::set<char>数据结构属性的方法。您还可以扩展它以计算所需的任何内容(请参见https://stackoverflow.com/a/54481338/5252007https://stackoverflow.com/a/54481338/5252007)。

这里是一个例子:

std::map

输出:

#include "map"
#include "iostream"


std::map<char, int> max_freq(const std::string& input)
{
    std::map<char, int> frequency;

    for (auto&& character : input)
    {
        ++frequency[character];
    }

    return frequency;
}


int main() {

    auto result = max_freq("abaabc");

    for(auto&& freq : result)
    {
        std::cout << freq.first << " : " << freq.second << "\n";        
    }
}

答案 2 :(得分:-1)

set<char> max_freq(map<char, int> frequency) // the return type of the function is 'set<char>'
{
    /*Logic Code*/

    return frequency; // frequency is 'map<char, int>' not 'set<char> '
}