c++ - 无法让数组正确更新

标签 c++ arrays

我正在尝试编写一个循环遍历字符串并计算每个字母被使用了多少的程序。问题是我无法让数组正确保存它。非常感谢任何帮助。

int main()
{
    string textRad = "";
    int histogram[ANTAL_BOKSTAVER];

    getline(cin, textRad);

    berakna_histogram_abs(histogram, textRad);

    cout << histogram[0] << endl;
    cout << histogram[2];

    return 0;
}

void berakna_histogram_abs(int histogram[], string textRad) 
{
    for(int i = 0; i < ANTAL_BOKSTAVER; i++) 
    {
        histogram[i] = 0;
    }

    for(int i = 0; i < textRad.length(); i++)
    {
        for(int j = 0; j < ANTAL_BOKSTAVER; j++)
        {
            int antal = 0;
            string alfabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

            if(char(toupper(textRad.at(i))) == alfabet.at(j))
            {
                antal++;
            }
            histogram[j] = antal;
        }
    }
}

最佳答案

这里考虑到 Javid 和 Tjofras 的回答是一个完整、更简单、更安全的示例:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

void berakna_histogram_abs(std::vector<int>& histogram, const std::string& textRad);

int main() {

    const int ANTAL_BOKSTAVER = 26; //Assumed value.

    std::string textRad;
    std::vector<int> histogram(ANTAL_BOKSTAVER, 0);

    std::getline(std::cin, textRad);

    std::transform(textRad.begin(), textRad.end(), textRad.begin(), toupper);
    berakna_histogram_abs(histogram, textRad);

    std::cout << histogram[0] << std::endl;
    std::cout << histogram[2];

    return 0;
}

void berakna_histogram_abs(std::vector<int>& histogram, const std::string& textRad) {

    static std::string alfabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    std::size_t s = alfabet.length();
    for(std::size_t i = 0; i < s; ++i) {
        histogram[i] = std::count(test_string.begin(), test_string.end(), alfabet[i]);
    }
}

关于c++ - 无法让数组正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18422387/

相关文章:

c++ - C++ 中的非连续数组指针

c++ - 如何获取 GDI 句柄列表

javascript - 将复选框数组传递给 $_GET 的替代方法 - 除了方括号之外

mysql - 如何在 MySQL 中模拟数组变量?

python - 任何人都知道 Python 中的一个伟大的稀疏一维数组库?

c++ - 找不到默认构造函数

c++ - "live"流的简单移动平均线 - 快速实现

C++ - 生成子类实例的父类(super class)构造函数

python - 将 numpy 数组转换为图像

c - 用 m 次不带位域的数据填充索引 n 处的数组