-8

I have a task to count many "a" letters in an array

so this is my code

#include <iostream>

#include <vector>
#include <algorithm>
using namespace std;
int main(){
    int i;
    int ch[10];
    cout<<"enter 10 letters"<<endl;
    for(i=0;i<10;i++){
        cin>>ch[i];
    }
    cout<<endl;cout<<endl;
    cout<<"this is the letter you entered"<<endl;
    cout<<endl;
    for(i=0;i<10;i++){
        cout<<(ch[i])<<endl;
    }
    vector<int> a = ch[10];
    int cnt;
    cnt = count(a.begin(), a.end(), "a");
    cout<<"many a's are = "<<cnt<<endl;

}

but it give me error [Error] conversion from 'int' to non-scalar type 'std::vector' requested

please help me, reference my code from https://www.tutorialspoint.com/cpp_standard_library/cpp_algorithm_count.htm

  • Try `std::copy(std::begin(ch),std::end(ch),std::begin(a));` instead of `vector a = ch[10];`. – user0042 Nov 26 '17 at 12:34
  • Expression `ch[10]` does not represent the array as a whole. Also, distinguish `int` and `char`, and character literal and string literal. –  Nov 26 '17 at 12:35
  • `vector a = ch[10];` Has 2 errors on it's own: 1) No conversion exists from an `int` (11th element of `ch` array) to `std::vector` 2) You are referencing an element outside of the bounds of the array - invoking undefined behavior. I would suggest you read a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Algirdas Preidžius Nov 26 '17 at 12:35
  • The name of the array is `ch`, not `ch[10]`, and `"a"` is an array of characters, not a character. – molbdnilo Nov 26 '17 at 12:36
  • no no no, I mean, I'll insert a character a into an array via cin, a also variable – Joen Doe Nov 26 '17 at 12:42
  • I do not understand c ++ but this is my homework from lecturer – Joen Doe Nov 26 '17 at 12:44

1 Answers1

2

For starters the array ch should be declared like

char ch[10];
^^^^

if you are going to type letters as the input.

This statement

vector<int> a = ch[10];

does not make sense. The initializer of the vector is non-existent element of the array ch. And moreover the class template std::vector does not have a non-explicit constructor that converts an object of the type int to the type std::vector<int>.

And in this statement

cnt = count(a.begin(), a.end(), "a");

you are trying to count how many times the string literal "a" that has the type const char[2] is encountered in an object of the type std::vector<int>.

There is no need to declare a vector that to count occurrences of the letter 'a'. You could just write

#include <iterator>

//...

char ch[10];

//...

auto cnt = std::count( std::begin( ch ), std::end( ch ), 'a' );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335