Итератор (string :: iterator) ведет себя как будто вне области видимости? - PullRequest
2 голосов
/ 05 марта 2012

У меня есть документы PDF, скопированные / вставленные в TXT в качестве входных данных, и я хочу построить дерево «Раздела».Каждый раздел содержит заголовок (например, «3.3. Оценка методов») и текст (все остальное до следующего заголовка).И то, и другое реализовано с помощью iterator_range (который я набрал с помощью string_range).

Я начал с функции в другом месте, которая возвращает мне номер заголовка + самое первое слово после него (в предыдущем примере он вернул бы «3.3 Evaluation»).и все остальное поставить под текст).Эта функция расширяет заголовок.

Все, что она делает, это делает первую полную остановку в тексте раздела и расширяет заголовок до последнего слова в тексте с большой буквы, также сокращая текст соответствующим образом.

Цикл while позволяет мне добраться до последнего.Если отлажено, оно отлично работает, пока ВНУТРИ цикла.Как только я оставлю это, итераторы облажались.Я не понимаю почему.

Вы можете попробовать запустить код самостоятельно, так как я снял с него все остальные зависимости - он работает так же и работает.

Строка temp должна быть причиной, поскольку это единственноевнутри области цикла while - но это не имеет никакого смысла, так как я копирую его в другую переменную, которая является единственной вещью, видимой итераторами.Другая переменная не выходит из области видимости, так почему же меняются итераторы?Я не могу придумать объяснения: - (

Это не буст, потому что необъяснимый std :: string :: iterator делает то же самое - класс iterator_range не имеет ничего общего с этим поведением ...

#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string_regex.hpp>
#include <boost/regex.h>


using namespace std;
using namespace boost;

typedef iterator_range<string::iterator> string_range;

int main() {
    string original_text("Mixed Initiative Dialogue Management 2.1 Motivation In naturally occurring human-human dialogues, speakers often adopt different dialogue strategies based on hearer characteristics, dialogue history, etc.For instance, the speaker may provide more guidance if the hearer is hav- ing difficulty making progress toward task completion, while taking a more passive approach when the hearer is an expert in the domain.Our main goal is to enable a spoken dialogue system to simulate such human be- havior by dynamically adapting dialogue strategies dur- ing an interaction based on information that can be au- tomatically detected from the dialogue. Figure 1 shows an excerpt from a dialogue between MIMIC and an ac- tual user where the user is attempting to find the times at which the movie Analyze This playing at theaters in Montclair. S and U indicate system and user utterances, respectively, and the italicized utterances are the output of our automatic speech recognizer.In addition, each system turn is annotated with its task and dialogue ini- tiative holders, where task initiative tracks the lead in the process toward achieving the dialogue participants' do- main goal, while dialogue initiative models the lead in determining the current discourse focus (Chu-Carroll and Brown, 1998). In our information query application do- main, the system has task (and thus dialogue) initiative if its utterances provide helpful guidance toward achieving the user's domain goal, as in utterances (6) and (7) where MIMIC provided valid response choices to its query in- tending to solicit a theater name, while the system has 97 dialogue but not task initiative if its utterances only spec- ify the current discourse goal, as in utterance (4). This dialogue illustrates several features of our adap- tive mixed initiative dialogue manager for dynamic");
    string_range text(original_text.begin(), original_text.end() );
    string first_sentence("Mixed Initiative Dialogue Management 2.1 Motivation In naturally occurring human-human dialogues, speakers often adopt different dialogue strategies based on hearer characteristics, dialogue history, etc.");
    regex capex("((^| )([A-Z][a-z]+|[A-Z]+) )"); // Capitalized word (or fullcapsed word)
    string_range capitalized_word;

    string::iterator unexplainable;
    int count = 0;
    while (find_regex(first_sentence, capex) ) { // Getting the last one
        capitalized_word = find_regex(first_sentence, capex);
        string temp(capitalized_word.end(), first_sentence.end() );
        first_sentence = temp;
        unexplainable = capitalized_word.begin(); // Here is fine
        count++;
    }
    if (count <= 1) return 0;
    string_range new_text_range(unexplainable, text.end()); // Here it gets full of junk... why??
    string new_string(new_text_range.begin(), new_text_range.end() );
    string_range new_text_range2(capitalized_word.begin(), text.end());
    return 0;
}

1 Ответ

3 голосов
/ 05 марта 2012

Ваша проблема в том, что вы смешиваете итераторы из разных последовательностей и пытаетесь создать новую последовательность из них. Итератор unexplainable указывает где-то в строке first_sentence, в то время как text.end() указывает на конец строки original_text.

Вот как может выглядеть память

      0123456789012345
      ----------------
   00 Hello World!0%&(
   16 %£$!*Bye world!0

Теперь скажите, что unexplainable указывает на 6, т.е. "Мир!" и text.end() указывает на 31, теперь, если вы создадите диапазон (а затем строку из этого диапазона), вы получите мусор, потому что полученная строка будет выглядеть следующим образом: "World!0%&(%£$!*Bye world!". Это только выдуманный пример, но я надеюсь, что вы поняли: Не смешивайте итераторы из разных последовательностей !!

Я добавлю еще одну подсказку бесплатно: не вычисляйте find_regex() дважды, измените цикл на что-то вроде:

do
{
  capitalized_word = find_regex(first_sentence, capex);
  if(capitalized_word)
  {
    // do stuff
  }
}while(capitalized_word);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...