0

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;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • 2
    Is there a reason you don't use `std::string` for your strings? Why do you declare an overload taking a `std::string` argument as a "helper for tests", but don't define (implement) or use it? – Some programmer dude Apr 14 '22 at 10:57
  • As for why pointers can't be used in the range `for` loop, it's because a pointer is really only a pointer to a single value or object. It's just by convention that `char*` can be used for nulll-terminated strings, but it might as well be pointing to a sequence of raw bytes or something completely different, and the compiler just don't know. – Some programmer dude Apr 14 '22 at 11:01
  • 1
    Pointers are not arrays, and arrays are not pointers. – molbdnilo Apr 14 '22 at 12:33
  • hey, that was a preset in the judge system, idk why it exists –  Apr 14 '22 at 16:55
  • so how can I fix this problem?, I cant change the data type i am receiving , as in const char * –  Apr 14 '22 at 16:56

1 Answers1

0

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;
}
choosyg
  • 774
  • 7
  • 23
  • 1
    Yes, you can use range loops with plain old arrays. (Try `char s[] = "hello"; for (auto c: s) cout << c;`) You can't use them with *pointers*, but that's a completely different thing. – molbdnilo Apr 14 '22 at 12:34
  • how can i fix the problem? –  Apr 14 '22 at 16:56