2017-11-26 5 views
-8

に私は、これは私のコードは「」アレイ

#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; 

} 

配列

には多くの「」の文字をカウントする作業をされているが、それは私にエラー [エラーを与える手紙を数えます非スカラー型「のstd ::ベクトル」から 'int型からの変換はhttps://www.tutorialspoint.com/cpp_standard_library/cpp_algorithm_count.htm

+0

を書くことができ;' '代わりにベクトルの= ch [10]; '。 – user0042

+0

式 'ch [10]'は配列全体を表していません。また、 'int'と' char'を区別し、文字リテラルと文字リテラルを区別します。 –

+0

'ベクトル a = ch [10];' 2つのエラーがあります:1) 'int'(' ch'配列の11番目の要素)から 'std :: vector 'への変換はありません。配列の境界の外側にある要素を参照して、未定義の動作を呼び出します。私は[良いC++の本](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)を読むことをお勧めします。 –

答えて

2

Foのから

私を助けてください、 参照私のコードを要求しましたrは、あなたが入力として文字を入力しようとしている場合、配列ch

char ch[10]; 
^^^^ 

のように宣言されなければならないスタータ。

この文

vector<int> a = ch[10]; 

は意味がありません。ベクトルの初期化子は配列chの存在しない要素です。また、クラステンプレートstd::vectorには、タイプintのオブジェクトをタイプstd::vector<int>に変換する非明示的なコンストラクタがありません。

そして、この文で

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

あなたはタイプconst char[2]がタイプstd::vector<int>のオブジェクトに遭遇されたこと回数を文字列リテラル"a"カウントしようとしています。

'a'という文字の出現をカウントするベクトルを宣言する必要はありません。あなただけの `のstd ::を試してみてくださいコピー(STD ::(CH)を開始し、STD ::終了(CH)、STD ::(a)の開始)

#include <iterator> 

//... 

char ch[10]; 

//... 

auto cnt = std::count(std::begin(ch), std::end(ch), 'a');