在地图中使用矢量时出错

Error when using vectors in a map

本文关键字:出错 地图      更新时间:2023-10-16

我正试图根据键将向量添加到地图中的某个位置。

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;