Использование векторной функции на элементе узла - PullRequest
0 голосов
/ 12 апреля 2019

Я пишу программу на C ++, где я беру строку из txt-файла и вставляю ее в vector<string> data, который находится внутри структуры (я делаю связанный список каждой отдельной строки). Технически, у меня есть цикл, который разбивает слова из предложения, которое я вношу, и помещаю их в вектор по одному.

Проблема, с которой я столкнулся, заключается в том, что я пытаюсь получить размер вектора через

int size;
size = current->data.size();

Текущий узел. Я получаю как неявное предупреждение о преобразовании, так и «Поток 1: EXC_BAD_ACCESS (code = EXC_I386_GPFLT)».

Может кто-нибудь объяснить, где я иду не так? Разве не возможно кодировать что-то подобное? Должен ли я просто создать переменную счетчика, чтобы отслеживать, сколько слов помещается в вектор? И какой будет наилучшая практика программирования для достижения этой цели?

Вот мой основной () файл


#include <iostream>
#include <fstream>
#include "SkipGram.hpp"

using namespace std;

int main() {
    string file;
    ifstream inFile;
    vector<string> sentence;
    string line;
    SkipGram control;
    int skip;
    int gram;

    cout << "Please enter file name:\n";
    cin >> file;
    inFile.open(file);

    while(!inFile.is_open()){   //makes sure we get a working file
        cout << "Error reading in file. Please try again.";
        cin >> file;
        inFile.open(file);
    }

    cout << "Please enter how many words you want skipped and the amount of grams:";
    cin >> skip >> gram;

    while(!inFile.eof()){
        getline(inFile, line);
        control.convert(line);
    }

    control.skipGramFunc(skip, gram);
    control.printSkipGram();

    return 0;



}

Вот мой .hpp файл

#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>

using namespace std;

class SkipGram{
public:
    SkipGram();
    void convert(string line);
    void skipGramFunc(int skip, int gram);
    void printSkipGram();

private:
    typedef struct sentence{
        vector<string> data;
        vector<string> result;
        int position;
        sentence* next;
    }* sentencePtr;

    sentencePtr first;
    sentencePtr current;
    int amount;
};

Вот мой .cpp файл

#include "SkipGram.hpp"

using namespace std;

SkipGram::SkipGram(){
    first = NULL;
    current = NULL;
    amount = 0;
}

void SkipGram::convert(string line){
    // go word by word through sentence and create a vector out of it
    // add into the sentence list
    sentencePtr newSentence = new struct sentence;


    if(first == NULL){
        current = newSentence;
        first = newSentence;
        amount++;
        newSentence->position = amount;
    }else {
        current = newSentence;
        amount++;
        newSentence->position = amount;
    }

        string word;
        int length = line.length();
        int i = 0;
        int front = 0;
        int temp;

        while( i <= length){
            temp = line.find(" ");
            if( temp == -1){
                break; //catches when sentence is done with
            }
            word = line.substr(front, temp);
            newSentence->data.push_back(word);
            temp++;
            line = line.erase(front, temp);
        } //END OF WHILE

    }



void SkipGram::skipGramFunc(int skip, int gram){
    // goes through word vector and rearranges them
    if(gram == 1){
        cout << "Need more than one gram!" << endl;
        return;
    }

    if(skip == 0 || gram == 0){
        cout << "Input cannot be 0!";
    }

    int size;
    int temp;
    int tempAmount = amount;

    current = first;
    skip++;

    while( tempAmount != 0){ // while loop goes through all the sentences

        size = current->data.size();
        size = size - skip; // size here essentially becomes a marker to find out where to stop the loop

        for(int i = 0; i < size; i++){ // for loop goes through all the words

            for(int j = 0; j < gram; j++){ // this loop checks to see if we got the right number of grams
                if(j == 0){ // are we on the first gram
                    current->result.push_back(current->data.at(i));
                }else { // we want skipped gram
                    temp = i + skip;
                    current->result.push_back(current->data.at(temp));
                } // END OF IF

            }// END OF GRAM IF

            current->result.push_back(",");

        }//END OF WORD FOR

        current = current->next;
        tempAmount--;
    }//END OF WHILE

}// END OF FUNCTION

void SkipGram::printSkipGram(){


    int tempAmount = amount;

    current = first;

    while(tempAmount != 0){
        int size = current->data.size();

        for(int i = 0; i <= size; i++){
            cout << current->data.at(i);
        };

    }//END OF WHILE

}

1 Ответ

0 голосов
/ 12 апреля 2019

Вы никогда не присваиваете next, но читаете его. После чего ваша программа демонстрирует неопределенное поведение путем доступа к значению неинициализированного объекта.

...