Write a function num_uniques that takes in a string and returns the number of unique characters in the string.
Hint: You can use a std::map to maintain a count of the characters.
#include <string>
using namespace std;
int num_uniques(string str) {
//code..
}
1
Expert's answer
2018-04-25T08:59:13-0400
#include <map> #include <string>
using namespace std;
int num_uniques(string str) { // Map store information about the count of characters map<char, int> chars;
const int strLen = str.length(); for (int i = 0; i < strLen; ++i) { // Try to insert new element in map with current symbol const auto insertRes = chars.insert(make_pair(str[i], 1));
/* If result of insert == false, then the symbol * already exist in the map * so we just increment its count */ if(!insertRes.second) ++(insertRes.first->second); }
// Count symbols that were repeated only once int numOfUniques = 0; for (const auto it : chars) if(it.second == 1) ++numOfUniques;
return numOfUniques; }
int main() { const string str = "AA BB C D E fF"; const int numOfUniques = num_uniques(str); printf("Num of unique characters: %d\n", numOfUniques);
Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…
APPROVED BY CLIENTS
"assignmentexpert.com" is professional group of people in Math subjects! They did assignments in very high level of mathematical modelling in the best quality. Thanks a lot
Comments
Leave a comment