使用单词键将多个行号的向量添加到我的地图中

Adding a vector of multiple line numbers to my map with a key of words

本文关键字:添加 向量 我的 地图 单词键      更新时间:2023-10-16

所以基本上我正在开发一个字典程序,该程序在文档中读取并将其与单词列表进行比较,如果找不到单词,我需要将单词添加到地图中,其中包含该单词出现在文档中的相应行号。所以我正在尝试这样做,但我无法得到预期的结果!这是我的代码:

while (ss >> word)
{
wordCheck = d.findWord(word, words);
if(!wordCheck)
{
doc.missingMap(word, lineNum);
}
}
doc.displayMap();
//this just breaks up each line and checks for the words

void document::missingMap(string word, int lineNum)
{
vector<int> numbers;
numbers.push_back(lineNum);
misspelled[word] = numbers; 
}

这是文档调用中的函数,它将把所有内容都放在地图中。我不知道我是否走在正确的轨道上,但如果有人可以帮助我,那就太棒了。 谢谢!

更多详细代码

文档类:

#pragma once
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <sstream>
#include <list>
using namespace std;
class document
{
private:
map<string, vector<int>> misspelled;
public:
document(void);
~document(void);
void missingMap(string word, int lineNum);
void displayMap();
};

文档.cpp文件

#include "document.h"

document::document(void)
{
map<string, vector<int> > misspelled;
}
document::~document(void){}
void document::missingMap(string word, int lineNum)
{
//if i declare it here it works but obviously i want to modify it everywhere in the          class
misspelled[word].push_back(lineNum);
}
void document::displayMap()
{
for (map<string, vector<int>>::iterator i = misspelled.begin(); i != misspelled.end(); i++)
{
cout << i->first << ": ";
for (vector<int>::iterator j = i->second.begin(); j != i->second.end(); j++)
{
cout << *j << endl;
}
}
}

输出:

debugging: 1
process: 2
removing: 2
programming: 3
process: 4
putting: 4

这就是我希望它输出但不知道如何输出的方式:

debugging: 1
process: 2 4
programming: 3
putting: 4
removing: 2

希望这有帮助

改为尝试misspelled[word].push_back(lineNum);

更改类声明,如下所示:

class document
{
private:
std::map<std::string,std::vector<int> > misspelled;
// ^^^^^^^^^^^^^^^^ !!!   
public:
document(void);
~document(void);
void missingMap(string word, int lineNum);
void displayMap();
};

在你的document类中,就像你现在所做的那样,你在每次调用missingMap()函数时都会用一个新的misspelled映射替换存储在映射中的vector,而不是向映射条目添加更多的行号(正如你打算的那样我猜)。

注意
您无需显式创建std::vector<int>实例作为对misspelled[word]的任何访问的初始条目,std::map为您处理。