teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

コードの間違い

2019/11/20 04:27

投稿

退会済みユーザー
answer CHANGED
@@ -1,58 +1,43 @@
1
1
  ```C++
2
+
2
- #include <iostream>
3
+ #include <iostream>
3
4
  #include <fstream>
4
5
  #include <string>
5
6
  #include <vector>
6
7
  #include <algorithm>
7
8
  using namespace std;
8
9
 
9
- //プロトタイプ宣言
10
- bool precede(string str1, string str2);
11
-
12
10
  //メイン関数
13
11
  void main() {
14
12
 
15
- ifstream inFile; //入力ファイル
13
+ ifstream inFile; //入力ファイル
16
- string word; //単語
14
+ string word; //単語
17
- vector<string> vector;//vector配列
15
+ vector<string> vector;//vector配列
18
16
 
19
- //入力ファイルを開く
17
+ //入力ファイルを開く
20
- inFile.open("test.txt");
18
+ inFile.open("test.txt");
21
19
 
22
- // 入力ファイルが開けなければ終了する
20
+ // 入力ファイルが開けなければ終了する
23
- if (!inFile) {
21
+ if (!inFile) {
24
- cout << "入力ファイルを開けません" << endl;
22
+ cout << "入力ファイルを開けません" << endl;
25
- return;
23
+ return;
26
- }
24
+ }
27
25
 
28
- //ファイルから単語を読み込む
26
+ //ファイルから単語を読み込む
29
- inFile >> word;
27
+ inFile >> word;
30
28
 
31
- //ファイルの末尾でなければ、以下の処理を繰り返す
29
+ //ファイルの末尾でなければ、以下の処理を繰り返す
32
- while (!inFile.eof()) {
30
+ while (!inFile.eof()) {
33
31
 
34
- //単語を格納する
32
+ //単語を格納する
35
- vector.push_back(word);
33
+ vector.push_back(word);
36
34
 
37
- //新しい単語を読み込む
35
+ //新しい単語を読み込む
38
- inFile >> word;
36
+ inFile >> word;
39
- }
37
+ }
40
38
 
41
- //vector配列に格納した単語を、長さ順にソートする
39
+ //vector配列に格納した単語を、辞書順にソートする
42
- sort(vector.begin(), vector.end(), precede);
40
+ sort(vector.begin(), vector.end());
43
-
44
- //結果を表示する
45
- for (unsigned i = 0; i < vector.size(); i++) {
46
- cout << vector[i] << endl;
47
- }
48
41
  }
49
42
 
50
- //単語の長さによって要素の大小を判定する
51
- bool precede(string str1, string str2)
52
- {
53
- if (str1.length() < str2.length())
54
- return true;
55
- else
56
- return false;
57
- }
58
43
  ```