2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C++】同じ文字列が出てくる回数を数える

Last updated at Posted at 2019-05-28

内容

 mapで文字列と出現回数を保持する辞書を作成して同じ文字列が入力されるとその回数を数えるというもの。自分用の備忘録として置いておきます。for文の使い方がちょっと特殊で最初見た時は困惑しました。多分こんな面倒なことしなくてもSTLとかに便利なライブラリやら関数やらがありそうです。環境はVisual Studio 2019です。

動作:
 文字列入力→出現回数出力→文字列入力→出現回数出力→...

▽サンプルコード▽

sample.cpp
# include <iostream>
# include <map>
# include <string>

using namespace std; // std::map~, std::cout~とかを省略する為

int main() {
	map<string, int> dict; // 文字列と出現回数の辞書作成

	int n; cin >> n; // 下for文のループ回数
	for (string x; n--; dict[x]++) { // 辞書内の文字列xに対応する出現回数を+1する
		cin >> x; // 文字列 x 入力
		cout << "入力文字列: " << x << ", 出現回数: " << dict[x] + 1 << "回" << endl;
	}
}

▽入力例▽

Input
10
orange
orange
apple
apple
grape
grape
apple
apple
orange
orange
grape

▽出力例▽

Output
10
orange
入力文字列: orange, 出現回数: 1
orange
入力文字列: orange, 出現回数: 2
apple
入力文字列: apple, 出現回数: 1
apple
入力文字列: apple, 出現回数: 2
grape
入力文字列: grape, 出現回数: 1
grape
入力文字列: grape, 出現回数: 2
apple
入力文字列: apple, 出現回数: 3
apple
入力文字列: apple, 出現回数: 4
orange
入力文字列: orange, 出現回数: 3
orange
入力文字列: orange, 出現回数: 4

orangeは4回、appleは4回、grapeは3回入力していてうまく機能しています。色々応用できそう。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?