【问题标题】:counting the letters "a" in an array计算数组中的字母“a”
【发布时间】:2017-11-26 12:32:30
【问题描述】:

我的任务是计算数组中的许多“a”字母

这是我的代码

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

}

但它给了我错误 [错误] 请求从“int”转换为非标量类型“std::vector”

请帮帮我, 从https://www.tutorialspoint.com/cpp_standard_library/cpp_algorithm_count.htm引用我的代码

【问题讨论】:

  • 试试std::copy(std::begin(ch),std::end(ch),std::begin(a)); 而不是vector&lt;int&gt; a = ch[10];
  • 表达式ch[10] 并不代表整个数组。另外,区分intchar,以及字符文字和字符串文字。
  • vector&lt;int&gt; a = ch[10]; 本身有 2 个错误:1) 不存在从 intch 数组的第 11 个元素)到 std::vector&lt;int&gt; 的转换 2) 您正在引用外部的元素数组的边界 - 调用未定义的行为。我建议你阅读good C++ book
  • 数组名是ch,不是ch[10]"a"是字符数组,不是字符。
  • 不不不,我的意思是,我会通过 cin 将一个字符 a 插入到数组中,也是一个变量

标签: c++ arrays count


【解决方案1】:

对于初学者,数组ch 应该声明为

char ch[10];
^^^^

如果您要输入字母作为输入。

此声明

vector<int> a = ch[10];

没有意义。向量的初始值设定项是数组ch 的不存在元素。此外,类模板std::vector 没有将int 类型的对象转换为std::vector&lt;int&gt; 类型的非显式构造函数。

在此声明中

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

您正在尝试计算类型为 const char[2] 的字符串文字 "a"std::vector&lt;int&gt; 类型的对象中遇到的次数。

无需声明一个向量来计算字母'a' 的出现次数。你可以写

#include <iterator>

//...

char ch[10];

//...

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多