在熟悉 C++ STL 时,我使用配对对象列表遇到了这个问题。
int count (std::string input, std::vector<std::string> screen){
std::string::iterator it = input.begin();
std::pair<std::string, int> freq[10];
std::list<std::pair<std::string,int> > freq2;
freq2.push_back(std::make_pair(*it,0)); //ERR:No instance of fn matches arg list
freq2.push_back(std::make_pair('S',0)); //ERR:No instance of fn matches arg list
freq2.push_back(std::make_pair("S",0)); //This is fine
freq[0] = std::make_pair(*it,0); //This is fine
freq[0] = std::make_pair("S",0); //This is fine
freq[0] = std::make_pair('S',0); //This is fine
return 1;
}
freq 和 freq2 都非常相似,只是 freq2 只是一个列表。 Freq 能够接受字符、字符串和迭代器指针,并且两个对 (freq,freq2) 都被声明为对。不知道为什么会这样,有什么提示吗?谢谢。
编辑:现在更有意义了,我得到的所有回复都非常有帮助,谢谢你们!
原文由 user899604 发布,翻译遵循 CC BY-SA 4.0 许可协议
类
std::basic_string
没有具有一个参数类型为char
的构造函数。所以这些语句无效在这些陈述中更准确地说,试图从 --- 类型的对象构建一个类型为
std::pair<std::string, int>
std::pair<char, int>
对象。这要求有一个std::string
类的构造函数,其参数类型为char
。但是没有这样的构造函数。至于这些说法
然后使用
std::basic_string
类的赋值运算符。该类有一个重载赋值运算符,它接受char
类型的对象。所以这些说法是正确的。
考虑以下示例
输出是
由于类
std::pair
具有模板赋值运算符,而类std::string
又具有具有 char 类型参数的赋值运算符,则此代码编译成功。例如,如果您要写
代替
you would get an error because there is no conversion from
std::pair<char, int>
tostd::pair<std::string, int>
because there is no constructor fromchar
tostd::string
.