在地图中使用矢量时出错
Error when using vectors in a map
我正试图根据键将向量添加到地图中的某个位置。
vector<string> words;
map<string, vector<string>> wordMap;
for (int i = 0; i < words.size(); i++) {
string word = words.at(i);
if (wordMap.find(word) == wordMap.end())
wordMap.insert(make_pair(word, vector<string>()));
vector<string> context = { "EMPTY" };
if (i == 0)
context = { "Beginning of words", words[i + 1], words[i + 2] };
else if(i == 1)
context = { "Beginning of words", words[i - 1], words[i + 1], words[i + 2] };
else if (i == words.size() - 2)
context = { words[i - 2], words[i - 1], words[i + 1], "End of words" };
else if(i == words.size() - 1)
context = { words[i - 2], words[i - 1], "End of words" };
else
context = { words[i - 2], words[i - 1], words[i + 1], words[i + 2] };
wordMap[word].push_back(context);
cout << context[0] << endl;
}
我在中的时间段不断收到以下错误
wordMap[word].push_back(context);
Error: no instance of overloaded function "std::vector<_Ty,_Alloc>::push_back[with_Ty=std::string,_Alloc=std::allocator<std::string>]" matches the argument list
argument types are: (std::vector<std::string, std::allocator<std::string>>)
object type is std::vector<std::string, std::allocator<std::string>>
程序中的其他一切都有效,如果你需要,我可以发布它,但唯一的错误是当我尝试使用push_back时。我需要使用push_back,因为我无法重新分配值。我必须将以前的所有值都放在那个键上,所以push_back是理想的。非常感谢您的帮助。
代替:
wordMap[word].push_back(context);
您应该附加新的矢量:
std::copy(context.begin(), context.end(), std::back_inserter(wordMap[word]));
另一件事是,你并不真正需要这个初始化:
if (wordMap.find(word) == wordMap.end())
wordMap.insert(make_pair(word, vector<string>()));
因为稍后CCD_ 1将添加值初始化元素。
当在map
实例上调用operator[]
时,如果给定键处不存在值,则总是添加一个新元素,然后返回对它的引用。
编辑:发生此问题的原因是wordMap[word]
的类型为vector<string>
,调用push_back
是正确的,但您需要为push_back提供一个字符串类型的值,但在这里wordMap[word].push_back(context);
,context
的类型为vector<string>
。
也许变化是这样的:
for(vector<string>::iterator iter = context.begin(); iter != context.end(); iter++) {
wordMap[word].push_back(*iter);
}
此外,我会使用指针来代替,因为最好将指向字符串向量的指针存储在堆中,而不是存储在堆栈中(例如:)
map<string, vector<string>*> wordMap;
...
vector<string>* context = new vector<string>();
...
wordMap[word] = context;
相关文章:
- 访问者访问变体并返回不同类型时出错
- 为什么不;名字在地图上是按顺序排列的吗
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- 基于多个条件处理地图中的所有元素
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 在C++中将矢量转换为嵌套地图
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 初始化地图时出错
- 当我尝试将一对插入地图时,Qt程序seg出错
- 在地图中使用矢量时出错
- 使用不可复制(但可移动)键移动地图分配时出错