我一直在尝试不同的技术来解决这个问题,而且我对C ++或一般的编程都很陌生。这个问题来自我正在阅读的一本名为“Accelerated C ++”的书,到目前为止,我只是在第3章,所以我试图用第3章所教的内容来解决这个问题。当我运行该程序时,它运行正常,但只要我输入一个单词,我就会出现分段错误。任何人都可以向我解释为什么会这样吗?另外,如果我的方法对我迄今所知的知识来说效率极低,暗示在章节边界内做更好的事情会很棒!
以下是代码:
#include <iostream>
#include <algorithm>
#include <ios>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
int main()
{
//ask for the first sentence to be typed in.
cout << "Please enter some words: ";
vector<string> word_storage;
vector<int> word_count;
string x;
int y = 0;
//words inputed pushed into vector(word_storage) or incremented if they exist
while(cin >> x) {
for(int i = 0; i <= y; i++) {
if(x != word_storage[i]) {
word_storage.push_back(x);
word_count.push_back(1);
} else {
word_count[i] += 1;
}
}
y++;
}
cout << endl;
//get size of word_storage
typedef vector<double>::size_type vec_sz;
vec_sz size = word_storage.size();
//system prints how many of each word exist
for(int j = 0; j <= size; j++) {
cout << "There are: " << word_count[j]
<< " of the word " << word_storage[j];
}
cout << endl;
return 0;
}
P.S。我为眼部疼痛编码道歉。
答案 0 :(得分:1)
向量包含自己的大小。我相信你可能有两个错误。首先,你的for循环中的'&lt; ='将离开向量的末尾,它应该是'&lt;'。其次,当你没有向word_storage添加单词时,你正在迭代y。
我觉得你觉得你应该看起来更像是:
while(cin >> x) {
for(int i = 0; i < word_storage.size(); i++) {
if(x != word_storage[i]) {
word_storage.push_back(x);
word_count.push_back(1);
} else {
word_count[i] += 1;
}
}
}
还可以进行一些其他改进,其中最重要的是使用结构将存储和计数绑定到同一个向量,并使用迭代器。当你到达那些章节时,请考虑一下。
答案 1 :(得分:0)
for(int i = 0; i <= y; i++) {
if(x != word_storage[i]) {
word_storage
是一个未初始化/空的向量。并且您尝试访问空向量导致分段错误。例如,在循环开始时,向量中没有任何内容可以对其进行下标操作。
如果[]
的大小超过word_storage
,请执行i
操作。