If you want to count how many times each character occurred then you can use std::string
instead of using " built in arrays and priority_queue<>
" as shown below. That is there is no need for priority_queue<>
. The program prints the output in the order as you desire.
Version 1: Using 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;
}
The output of the above program is as follows:
a-3
n-3
o-2
p-1
s-1
i-1
g-1
h-1
r-1
The above(version 1) program counts small and capital letters separately. So for example the character A
and the character a
are different.
If you still want to use built in array instead of std::string
then you can use the following program. Note that still you don't need priority_queue
.
Version 2: Using built in array
#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;
}
The ouptut of the above(version 2) program is:
a-3
n-3
o-2
p-1
s-1
i-1
g-1
h-1
r-1