错误 C2679:二进制'=':找不到采用类型为"std::basic_string的右侧操作数的运算符

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::basic_string

本文关键字:string basic 运算符 std 操作数 类型 二进制 C2679 找不到 错误      更新时间:2023-10-16

我曾尝试使用unordered_map的C++代码编写电话簿,但遇到了问题。在这段代码的开头有一个我无法理解的错误。当我试图运行它时,我得到了这个错误:

错误1错误C2679:二进制"="

有人能帮我吗?

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <hash_map>
#include <algorithm>
using namespace std;
int main()
{
    unordered_map<string, pair< string,vector<string>>>contact;
    string name, number, address;
    cin >> name >> number>>address;
    contact[name]=make_pair(number, address);
    unordered_map<string, pair< string, vector<string>>> ::iterator it;
    it = contact.begin();
    while (it != contact.end())
    {
        cout << it->first;
        it++;
    }
    return 0;
}

您将contact声明为unordered_map<string, pair< string,vector<string>>>
此处插入contact[name]=make_pair(number, address);
contact[string] = make_pair(string, string)。必须是
contact[string] = make_pair(string, vector<string>)

要么改变容器的定义,比如

unordered_map<string, pair< string, string>>contact;

或者,如果你真的需要你的address成为vector,那么

contact[name] = make_pair(number, std::vector<string>{address});

如果您使用c++11或更高版本,则可以使用auto

auto it = contact.begin();

而不是

unordered_map<string, pair< string, vector<string>>> ::iterator it;
it = contact.begin();