while, ex6.12

版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 4.0

Example

将一个数组拷贝到另一个数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

using std::cin;
using std::cout;
using std::endl;


int main()
{

int arr[5] = { 1, 2, 3, 4, 5 };
int *source = arr;
size_t sz = sizeof(arr) / sizeof(*arr);
int *dest = new int[sz];
while (source != arr + sz)
{
*dest++ = *source++;
}

// test
int *dp = dest - sz;
for (size_t i = 0; i < sz; ++i)
{
cout << *dp << endl;
dp++;
}
return 0;
}

outputs

1
2
3
4
5
1
2
3
4
5

Exercise 6.12

输入一些单词,统计里面单词出现的次数。

如:how, now now now brown cow cow
则需输出: how 1次,now 3次,brown 1次,cow 2次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <string>
#include <vector>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

bool isCharacter(char ch)
{

return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}

int main()
{

// 把单词存入vector,并忽略非字母
string str;
getline(cin, str);
const char *cp = str.c_str();
vector<string> raw;
string tmp = "";
while (*cp) {
if (isCharacter(*cp))
{
tmp += *cp++;
if (*cp != '\0')
{
continue;
}
}

if (!tmp.empty())
{
raw.push_back(tmp);
tmp = "";
}
++cp;
}

// 统计各单词出现的次数
vector<string> unique;
vector<int> cnt;
unique.push_back(raw[0]);
cnt.push_back(0);
for (vector<string>::size_type i = 0; i != raw.size(); ++i)
{
bool found = false;
for (vector<string>::size_type j = 0; j != unique.size(); ++j)
{
if (raw[i] == unique[j])
{
++cnt[j];
found = true;
}
}
if(!found)
{
unique.push_back(raw[i]);
cnt.push_back(1);
}
}

// 输出
int max = cnt[0];
int max_index = 0;
vector<int>::size_type i = 0;
for (; i != cnt.size(); ++i)
{
cout << "单词:" << unique[i] << ",出现次数为:" << cnt[i] << endl;
if (max < cnt[i])
{
max = cnt[i];
max_index = i;
}
}
cout << endl <<"出现最多的是:"<< unique[max_index] << ",次数为:" << cnt[max_index] << endl;

return 0;
}

outputs

1
2
3
4
5
6
7
how, now now now brown cow cow↙
单词:how,出现次数为:1
单词:now,出现次数为:3
单词:brown,出现次数为:1
单词:cow,出现次数为:2

出现最多的是:now,次数为:3