저는 메모리 관리에별로 좋지 않습니다. 누군가 내가 왜 EXC_BAD_ACCESS (코드 = 1 ...) 오류가 발생하는지 설명 할 수 있기를 바랍니다. Xcode는 getWord() 메서드를 호출 할 때 오류가 발생한다고 말합니다.EXC_BAD_ACCESS, getter를 호출하십시오.
트라이 데이터 구조를 구현할 때 노드에서 단어를 가져 오려고하면 오류가 발생합니다. 내 문제는 내 add 또는 addPhrase 메서드로 생각하지만 무슨 일이 일어나고 있는지 파악할 수 없다. 모든 제안을 부탁드립니다.
트리는 및 노드 클래스 :
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
class Node
{
private:
string word;
bool endOfSentence = false;
int weight = -1;
public:
vector<Node> children = {};
Node() {
this->setWord("");
}
Node(string s){
this->setWord(s);
}
string getWord(){
return this->word;
}
/*vector<Node> getChildren() { //children private
return this->children;
}*/
void setWord(string s) {
this->word = s;
}
void setEOS(){
this->endOfSentence = true;
}
void setWeight(int weight){
this->weight = weight;
}
};
class Trie
{
public:
Node root = *new Node();
string get(string p) {
string s = "stub";
return s;
}
void add(vector<string> phrase, int weight){
Node current = this->root;
vector<string> sentence = phrase;
int w = weight;
int found = -1;
for (int i = 0; i < current.children.size(); i++) {
if (phrase[0] == current.children[i].getWord()) {
found = i;
}
}
if (found >= 0) {
current = current.children[found];
sentence.erase(sentence.begin());
add(sentence,w);
}
else {
addPhrase(sentence,w);
}
}
void addPhrase(vector<string> phrase, int weight) {
Node current = this->root;
for (int i = 0; i < phrase.size(); i++) {
Node temp = *new Node(phrase[i]);
current.children.push_back(temp);
current = current.children[current.children.size() - 1];
if (i == phrase.size() - 1) {
current.setEOS();
current.setWeight(weight);
}
}
}
};
주요 - 단지 첫 번째 노드에서 말씀을 시도합니다.
#include "Trie.cpp"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char* argv[]) {
// Initialize trie up here
Trie myTrie = *new Trie();
// parse input lines until I find newline
for(string line; getline(cin, line) && line.compare("");) {
stringstream ss(line);
string string_weight;
ss >> string_weight;
int weight = stoi(string_weight);
// I am just going to put these words into a vector
// you probably want to put them in your trie
vector<string> phrase = {};
for(string word; ss >> word;) {
phrase.push_back(word);
}
myTrie.add(phrase, weight);
}
// parse query line
string query;
getline(cin, query);
cout << myTrie.root.children[0].getWord() << endl;
return 0;
}
완료되지 않음 (필요 [mcve])하지만 당신은 세 가지 위반 규칙에 취약하다. [Three of Rule은 무엇입니까?] (https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – user4581301
이 줄은 의심스러워 보입니다. Node root = * new Node(); // 왜 인스턴스화하지 않는가? Node root; 대신에? – kvr
@kvr은 두 가지 방법 모두 시도했지만 차이점을 두지 않았습니다. 나는 그것을 되돌려 놓고 잊었다. – Dez