简体   繁体   English

C++ Primer 5th Edition Exercise 1.23 关于我找到的解决方案的问题

[英]C++ Primer 5th Edition Exercise 1.23 Question about the Solution I Found

The exercise: Write a program that reads several transactions and counts how many transactions occur for each ISBN.练习:编写一个程序,读取多个事务并计算每个 ISBN 发生的事务数。

The answer I found on Github:我在Github上找到的答案:

#include <iostream>
#include "include/Sales_item.h"

int main()
{
    Sales_item currItem, valItem;
    if (std::cin >> currItem)
    {
        int cnt = 1;
        while (std::cin >> valItem)
        {
            if (valItem.isbn() == currItem.isbn())
            {
                ++cnt;
            }
            else
            {
                std::cout << currItem << " occurs " << cnt << " times " << std::endl;
                currItem = valItem;
                cnt = 1;
            }
        }
        std::cout << currItem << " occurs "<< cnt << " times " << std::endl;
    }
    return 0;
}

For example if the input ISBN is like this:例如,如果输入 ISBN 是这样的:

A A B A B C

The output would be: output 将是:

A occurs 2 times
B occurs 1 times
A occurs 1 times
B occurs 1 times
C occurs 1 times

Which isn't quiet right because they're not properly grouped.这不是正确的,因为它们没有正确分组。 The excercise didn't specify that records for each ISBN should be grouped together.练习没有指定每个 ISBN 的记录应该组合在一起。 (Though it's specified in the next exercise.) (虽然它在下一个练习中指定。)

I haven't found a right solution online yet.我还没有在网上找到合适的解决方案。 I've been thinking about this excercise for a while and still don't have much clue on how to solve it.我已经考虑这个练习一段时间了,但仍然不知道如何解决它。

I've only learned about while, for, if so far.到目前为止,我只了解了 while, for, if。 This seemingly easy exercise is kind of a challenge for me.这个看似简单的练习对我来说是一种挑战。 Hope you guys can give me, a beginner some clue about it.希望你们能给我一个初学者一些线索。 Thanks in advance!提前致谢!

use a std::map<char, int> chcounts;使用std::map<char, int> chcounts; where the key is the character.其中键是字符。

You can then do然后你可以做

  chcounts[ch]++;

this takes advantage of the fact that if you reference a map element using [] and the entry does not exist it will get created and default initialized这利用了这样一个事实,即如果您使用 [] 引用 map 元素并且该条目不存在,它将被创建并默认初始化

or if you have strings do或者如果你有字符串

 std::map<std::string, int> counts;

 ....
 counts[isbn]++;

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

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