使用单词键将多个行号的向量添加到我的地图中
Adding a vector of multiple line numbers to my map with a key of words
所以基本上我正在开发一个字典程序,该程序在文档中读取并将其与单词列表进行比较,如果找不到单词,我需要将单词添加到地图中,其中包含该单词出现在文档中的相应行号。所以我正在尝试这样做,但我无法得到预期的结果!这是我的代码:
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
为您处理。
相关文章:
- 添加存储在向量中的大整数的函数出现问题
- 不允许在向量中添加更多元素
- 如何将元素添加到向量的字符串位置
- 有没有办法向这个向量添加元素?
- 这种方式是否可以接受向向量添加unique_ptr?
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- C++ 将子类的对象添加到父类的向量中
- 如何在提升间进程中构建具有给定计数的向量并向其添加元素
- 将不同类型的变量添加到向量中
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- 使用 std::transform 将向量向量 (a) 添加到另一个向量向量 (b)
- 继承层次结构并将元素添加到向量
- 测试驱动开发 c++:如何将对象添加到向量中,将歌曲添加到播放列表并对其进行测试
- 如何将对象添加到类中的静态向量
- 对象如何将自身添加到对象类中的向量中?
- 为什么我们需要在优先级队列声明中添加一个向量作为参数?
- C++ 如何在向量中添加向量?vector.push_back( 向量<> )?
- 如何在CUDA内核中添加向量元素
- 向 NS2 添加向量;编译器错误
- 向向量添加向量