[英]facing error in converting character storing array to hashmap<int, char> and then to heap. then printing the character and number of their frequency
在这个问题中,我假设。 arr = {'a', 'a', 'b', 'c', 'c'}。 然后 unordered_map 会将其转换为 a-> 3, b-> 1, c-> 2. 然后我将其附加到最大堆 3-> a, 2-> c, 1-> 我应该是这个但我想要将结果打印为 abc,但我面临错误。 需要帮忙!!
代码在下面的链接中。 我不知道为什么我的代码不接受。 https://hastebin.com/mamudogizo.cpp
#include <bits/stdc++.h>
using namespace std;
int main()
{
unordered_map<char, int> mp;
priority_queue<pair<int, char>> mheap;
char arr[] = {'a','a','a','b','c','c'};
for (int i = 0; i < 6; ++i)
{
mp[arr[i]]++;
}
for (auto i = mp.begin(); i != mp.end(); i++)
{
mheap.push({i->first, i->second});
}
pair<int, char> curr = mheap.top();
cout<< curr.second;
return 0;
}
如果您想计算每个字符出现的次数,那么您可以使用std::string
而不是使用“内置数组和priority_queue<>
”,如下所示。 那就是不需要priority_queue<>
。 该程序按您希望的顺序打印输出。
版本 1 :使用std::string
#include <iostream>
#include <map>
int main() {
std::string inputString = "anoopsinghrana";
//std::cout<<"Enter a string: ";
//std::cin>> inputString;
//this map maps the char to their respective count
std::map<char, int> charCount;
for(char &c: inputString)
{
charCount[c]++;
}
std::size_t i = 0;
//just go through the inputString instead of map
for(char &c: inputString)
{
std::size_t index = inputString.find(c);
if(index != inputString.npos && (index == i)){
std::cout << c <<"-" << charCount.at(c)<<std::endl;
}
++i;
}
return 0;
}
上述程序的输出如下:
a-3
n-3
o-2
p-1
s-1
i-1
g-1
h-1
r-1
上述(版本 1)程序分别计算小写和大写字母。 例如,字符A
和字符a
是不同的。
如果您仍然想使用内置数组而不是std::string
那么您可以使用以下程序。 请注意,您仍然不需要priority_queue
。
版本 2 :使用内置数组
#include <iostream>
#include <map>
int myFind(char arr[], int len, int seek)
{
for (int i = 0; i < len; ++i)
{
if (arr[i] == seek) return i;
}
return -1;
}
int main() {
char arr[] = {'a','n','o','o','p','s','i','n','g','h','r','a','n','a'};
std::map<char, int> charCount;
for(int i = 0; i < sizeof(arr) / sizeof(char); ++i)
{
charCount[arr[i]]++;
}
int k = 0;
//just go through the inputString instead of map
for(int i = 0; i < sizeof(arr) / sizeof(char); ++i)
{
//std::size_t index = inputString.find(arr[i]);
int index = myFind(arr,sizeof(arr) / sizeof(char),arr[i]);
if(index != -1 && (index == k)){
std::cout << arr[i] <<"-" << charCount.at(arr[i])<<std::endl;
}
++k;
}
return 0;
}
上述(版本 2)程序的输出是:
a-3
n-3
o-2
p-1
s-1
i-1
g-1
h-1
r-1
您的地图从角色映射到其计数器,并且队列由计数器排序,因此当您将项目从地图推送到队列时,您需要替换first
和second
:
for (auto i = mp.begin(); i != mp.end(); i++)
{
mheap.push({ i->second, i->first });
}
另请注意,您仅打印队列中的第一个元素。 如果你想把它们全部打印出来(按顺序),你需要迭代它。 例如:
while (!mheap.empty())
{
pair<int, char> curr = mheap.top();
cout << curr.second << endl;
mheap.pop();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.