0

I have a big file in my results. I want to look for words around a specific word in this file. For example, if I have a file like this: I am going home they are going school sam is going to lunch

How can I get words before and after "going" and save it in a hash using C++.

Pendo826
  • 1,002
  • 18
  • 47

1 Answers1

2

You can just read the file word by word, always keeping N words as context. You can store the context in a std::deque which allows a rolling context

const int N = 10;
std::deque<std::string> words_before, words_after;
std::string current_word, w;

// prefetch words before and after
for (int i = 0; i < N; ++i) {
    std::cin >> w;
    words_before.push_back(w);
}

std::cin >> current_word;

for (int i = 0; i < N - 1; ++i) {
    std::cin >> w;
    words_after.push_back(w);
}

// now process the words and keep reading
while (std::cin >> w) {
    words_after.push_back(w);
    // save current_word with the words around words_before, words_after
    words_before.pop_front();
    words_before.push_back(current_word);
    current_word = words_after.front();
    words_after.pop_front();
}
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198