我正试图将向量添加到地图中与键相对应的位置。
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是理想的选择。非常感谢您的帮助。
vector<string>
推入到另一个vector<string>
中。你需要一个字符串作为参数。你能把 context 定义成 stringstream,随着进程的进行添加内容,然后只需执行wordMap[word].push_back(context.str());
即可吗? - RyanPstd::copy(context.begin(), context.end(), std::back_inserter(wordMap[word]));
应该可以完成此操作 (需要包含头文件#include <iterator>
和#include <algorithm>
)。 - Max LybbertwordMap.find(word) ...
的代码是完全多余的,可以删除。 - Slava