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

750 Views Asked by At

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;
}
1

There are 1 best solutions below

2
On

You just can't use range based for loops with plain old arrays. In your case you could use std::string_view as a wrapper around your char array:

const char* in = "hallo welt";

std::string_view sv(in);

for(const auto& x: sv){
  std::cout<<"char:"<<x<<std::endl;
  if(x == 'h')
    std::cout<<"h-detected"<<std::endl;
}