分词错误-比较不同的单词在c++输入中出现的次数

segmentation fault - Compare how many times distinct words appear in inputs C++

本文关键字:输入 c++ 单词 错误 比较 分词      更新时间:2023-10-16

我一直在尝试不同的技术来解决这个问题,而且我对c++或一般编程相当陌生。这个问题来自于我正在读的一本叫做"加速c++"的书,到目前为止我只读到了第三章,所以我只尝试用第三章教的东西来解决这个问题。当我运行程序时,它运行得很好,但只要我输入一个单词,我就会出现分割错误。有人能给我解释一下为什么会这样吗?此外,如果我的方法与我所知道的知识到目前为止是极其低效的,暗示一个更好的方法来做事情在章节的边界将是伟大的!

代码如下:

#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;
}

注:我提前为这些难看的代码道歉。

向量包含自己的大小。我相信你可能有两个bug。首先,如果for循环中的'<='要从vector的末尾移走,它应该是'<'。第二,当你没有向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;
        }
    }
}

还可以进行其他一些改进,其中最重要的是使用结构体将存储和计数绑定到同一个vector,并使用迭代器。

for(int i = 0; i <= y; i++) {
        if(x != word_storage[i]) {

word_storage是一个未初始化的空向量。而你试图访问一个空向量会导致分割错误。例如,在循环开始时,vector容器中没有可对其进行下标操作的对象。

如果word_storage的大小大于i,则对[]进行操作