Значения не хранятся в векторе - не уверен, что здесь происходит

0

Я работаю над проблемой, когда мне нужно хранить некоторые значения в векторе, вложенном в карту, но значения не сохраняются. Структура карты Map <Vector<char> >

Я пытаюсь вставить только код, соответствующий этой проблеме, потому что он находится в более широком контексте, но я подозреваю, что у меня что-то не хватает. Любая помощь будет оценена по достоинству.

Благодарю.

EDITS: Я использую библиотеки Stanford CS106B в этом вопросе, которые предоставляют интерфейсы для Map, Vector, getValue и добавляют:

     * Constructor: Map
     * Usage: Map<int> map;
     *        Map<int> map(500);
     *        Map<string> *mp = new Map<string>;
     * -----------------------------------------
     * The constructor initializes a new empty map. The optional 
     * argument is a hint about the expected number of entries
     * that this map will hold, which allows the map to configure 
     * itself for efficiency at that size.  If not specified, a 
     * reasonable default is used and the map will adapt as entries 
     * are added. The explicit keyword is used to prevent  
     * accidental construction of a Map from an integer.
     * Raises an error if sizeHint is negative.
     */
    explicit Map(int sizeHint = 101);


     * Constructor: Vector
     * Usage: Vector<int> vec;
     *        Vector<student> dormlist(200);
     *        Vector<string> *vp = new Vector<string>;
     * -----------------------------------------------
     * The constructor initializes a new empty vector. The optional 
     * argument is a hint about the expected number of elements that
     * this vector will hold, which allows vector to configure itself
     * for that capacity during initialization.  If not specified, 
     * it is initialized with default capacity and grows as elements 
     * are added. Note that capacity does NOT mean size, a newly 
     * constructed vector always has size() = 0. A large starting 
     * capacity allows you to add that many elements without requiring 
     * any internal reallocation. The explicit keyword is required to 
     * avoid accidental construction of a vector from an int.
     */
     explicit Vector(int sizeHint = 0);

getValue находится в интерфейсе карты, поэтому добавляется для обоих из них...

     * Member function: getValue
     * Usage: value = map.getValue(key);
     * ---------------------------------
     * If key is found in this map, this member function returns the 
     * associated value.  If key is not found, raises an error. The
     * containsKey member function can be used to verify the presence 
     * of a key in the map before attempting to get its value.
     */
    ValueType getValue(string key);

И добавьте как для карты, так и для вектора...

     * Member function: add
     * Usage: map.add(key, value);
     * ---------------------------
     * This member function associates key with value in this map.
     * Any previous value associated with key is replaced by this new
     * entry. If there was already an entry for this key, the map's
     * size is unchanged; otherwise, it increments by one.
     */
    void add(string key, ValueType value);


    /*
     * Member function: add
     * Usage: vec.add(value);
     * ----------------------
     * This member function adds an element to the end of this vector. 
     * The vector size increases by one.
     */
    void add(ElemType elem);


/* Private Instance Variables */
int seed_length;
char letter;
//Map <Vector<char> > map;

/* Function Prototypes */
string promptUserForFile(ifstream & infile);
char nextCharacter(char letter);
void storeInVector(string sequence, char letter, Map<Vector<char> > map);

int main() {

ifstream infile;
promptUserForFile(infile);

// Ask what order of Markov model to use.
cout << "What order of Markov model should we use? ";
cin >> seed_length;

// Store sequences in a map.
string sequence;
Map<Vector<char> > map;

for (int i = 0; i < seed_length; i++) {

    letter = infile.get();
    sequence += nextCharacter(letter);

}

while (infile.eof() == false) {

    letter = infile.get();
    storeInVector(sequence, letter, map);

    sequence.erase(0,1);
    char next_letter = nextCharacter(letter);
    sequence += next_letter;

}
}

И функция storeInVector - вот что вызывает проблему...

void storeInVector(string sequence, char letter, Map<Vector<char> > map) {

cout << sequence << endl;
cout << letter << endl;

Vector<char> vector(200); // I tried to specify size because it wasn't being populated... so I thought this may help

if (map.containsKey(sequence)) {

    // Insert the sequence that comes after it into the vector.
    map.getValue(sequence).add(letter);

} else {

    // Create a new key and vector.
    map.add(sequence, vector);
    map.getValue(sequence).add(letter);

}
}
  • 0
    Да, пожалуйста, покажите нам соответствующую часть определения Map , например, getValue и add .
  • 0
    Также добавьте нестандартную функцию add / gerValue
Показать ещё 5 комментариев
Теги:

1 ответ

1
Лучший ответ

Передайте map по ссылке: void storeInVector(string sequence, char letter, Map<Vector<char> >& map).

Как и в коде, каждый вызов storeInVector создаст копию Map>, и ваш оригинал останется нетронутым.

РЕДАКТИРОВАТЬ:

Не забудьте также изменить объявление функции (благодаря @user3175411)

  • 0
    Когда я пытаюсь передать карту по ссылке, выдается сообщение об ошибке «Symbol Not Found»: неопределенные символы: «storeInVector (std :: basic_string <char, std :: char_traits <char>, std :: allocator <char >> char, Map <Vector <char>>) ", на которую ссылаются из: Main () в assignment_2_part_1.o ld: символ (ы) не найдены
  • 0
    @marchon Как вы связываете эти библиотеки?
Показать ещё 11 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню