jeudi 14 avril 2022

How to iterate through a range-based for loop when the data type of the array is const char *?

I am trying to solve the following question: https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/train/cpp in C++.

When I try to iterate over a range based for loop I get the following error ->

In file included from main.cpp:6:
./solution.cpp:14:13: error: invalid range expression of type 'const char *'; no viable 'begin' function available
  for(auto x: in){
            ^ ~~
1 error generated.

The code ->

Also , further on I am also encountering an error while comparing, if(x!=' ') that I am comparing wrong data types, I am trying to understand the dereferencing concept and its escaping my understanding. can someone break down the explanation for me please?

#include <unordered_map>

#include <string.h>
using namespace std;

size_t duplicateCount(const std::string& in); // helper for tests

size_t duplicateCount(const char* in)
  
{ 

  unordered_map<char , int> hash;
  
  for(auto x: in){
    cout<<"char:"<<x<<endl;
    if(hash[x]>=0){
      hash[x]+=1;
    } else {
        if(x!=" "){
        
        hash[x]=0;
      }
    }
  }

  int ct=0;
  for(auto x:hash){
    if(x.second>1){
      ct++;

    }
  }
  return ct;
}

Aucun commentaire:

Enregistrer un commentaire