简体   繁体   English

计算C ++中相同数组值的出现次数

[英]Counting occurences of same array value in C++

I recently have been building a program where: 我最近一直在建立一个程序,其中:

  1. A user is asked to enter a number that will represent the size of a character array. 要求用户输入代表字符数组大小的数字。
  2. Then they are asked whether they will want the program to fill the values automatically, or they could press M so they could enter the values manually. 然后询问他们是否希望程序自动填充值,或者他们可以按M以便他们可以手动输入值。 They may only enter a-zA-Z values, or they will see an error. 它们可能只输入a-zA-Z值,否则会看到错误。
  3. At the end of the program, I am required to count every duplicate value and display it, for example: 在程序结束时,我需要计算每个重复值并显示它,例如:

An array of 5 characters consists of A;A;A;F;G; 5个字符的数组由A;A;A;F;G;

The output should be something like: 输出应该是这样的:

A - 3

F - 1

G - 1

I could do this easily, however, the teacher said I may not use an additional array, but I could make a good use of a few more variables and I also can't use a switch element. 我可以很容易地做到这一点,但是,老师说我可能不会使用额外的数组,但我可以很好地利用更多的变量,我也不能使用开关元素。 I'm totally lost and I can't find a solution. 我完全失去了,我找不到解决方案。 I've added the code down below. 我在下面添加了代码。 I have done everything, but the counting part. 我做了一切,但计数部分。

#pragma hdrstop
#pragma argsused

#include <tchar.h>
#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>

void main() {
int n, i = 0;
char masiva_izvele, array[100], masiva_burts;
cout << "Enter array size: ";
cin >> n;

clrscr();

cout << "You chose an array of size " << n << endl;
cout << "\nPress M to enter array values manually\nPress A so the program could do it for you.\n\n";

cout << "Your choice (M/A): ";
cin >> masiva_izvele;

if (masiva_izvele == 'M' || masiva_izvele == 'm') {
    clrscr();
    for (i = 0; i < n; i++) {
        do {
            cout << "Enter " << i + 1 << " array element: ";
            flushall();
            cin >> masiva_burts;
            cout << endl << int(masiva_burts);
            if (isalpha(masiva_burts)) {
                clrscr();
                array[i] = masiva_burts;

            }
            else {
                clrscr();
                cout << "Unacceptable value, please enter a value from the alphabet!\n\n";
            }
        }
        while (!isalpha(masiva_burts));
    }


}
else if (masiva_izvele == 'A' || masiva_izvele == 'a') {
    clrscr();
    for (i = 0; i < n; i++) {

        array[i] = rand() % 25 + 65;

    }
}

clrscr();

cout << "Masivs ir izveidots! \nArray size is " << n <<
    "\nArray consists of following elements:\n\n";

for (i = 0; i < n; i++) {

    cout << array[i] << "\t";

}         



cout << "\n\nPress any key to view the amount of every element in array.";

//The whole thing I miss goes here, teacher said I would need two for loops but I can't seem to find the solution.

getch();

}

I would be very thankful for a solution so I could move on and forgive my C++ amateur-ness as I've picked this language up just a few days ago. 我非常感谢一个解决方案,所以我可以继续并原谅我的C ++业余爱好者,因为我几天前就选择了这种语言。

Thanks. 谢谢。

EDIT: Edited title to suit the actual problem, as suggested in comments. 编辑:编辑标题以适应实际问题,如评论中所建议。

One possible way is to sort the array, and then iterate over it counting the current letter. 一种可能的方法是对数组进行排序,然后迭代计数当前字母。 When the letter changes (for example from 'A' to 'F' as in your example) print the letter and the count. 当字母改变时(例如,从你的例子中的'A''F' )打印字母和计数。 Reset the counter and continue counting the next character. 重置计数器并继续计算下一个字符。

The main loop should run foreach character in your string. 主循环应该在字符串中运行foreach字符。

The secondary loop should run each time the main "passes by" to check if the current letter is in array. 每次主“传递”时,辅助循环应该运行,以检查当前字母是否在数组中。 If it's there, then ++. 如果它在那里,那么++。

Assuming upper and lower case letters are considered to be equal (otherwise, you need an array twice the size as the one proposed: 假设大写和小写字母被认为是相等的(否则,您需要一个比建议大小两倍的数组:

std::array<unsigned int, 26> counts; //!!!

// get number of characters to read

for(unsigned int i = 0; i < charactersToRead; ++i)
{
    char c; // get a random value or read from console
    // range check, calculate value in range [0; 25] from letter...

    // now the trick: just do not store the value in an array,
    // evaluate it  d i r e c t l y  instead:
    ++counts[c]; 
}

// no  a d d i t i o n a l  array so far...

char c = 'a';
for(auto n : counts)
{
    if(n > 0) // this can happen now...
    {
        // output c and n appropriately! 
    }
    ++c; // only works on character sets without gaps in between [a; z]!
         // special handling required if upper and lower case not considered equal!
}

Side note: (see CiaPan's comment to the question): If only true duplicates to be counted, must be if(n > 1) within last loop! 旁注:(参见CiaPan对该问题的评论):如果只计算真正的重复项,则必须在最后一个循环中if(n > 1)

Add the array char chars[52] and count chars in this array. 添加数组char chars[52]并计算此数组中的字符数。 Then print out chars corresponding to the array, which count is more than 1. 然后打印出与数组对应的字符,其数量大于1。

std::unordered_map<char, int> chars;
...
char c = ...;
if ('A' <= c && c <= 'Z')
  ++chars[c];
else if ('a' <= c && c <= 'z')
  ++chars[c];
else
  // unexpected char
...
for (const auto p : chars)
  std::cout << p.first << ": " << p.second << " ";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM