C 对列表

新手上路,请多包涵

在熟悉 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 许可协议

阅读 448
2 个回答

std::basic_string 没有具有一个参数类型为 char 的构造函数。所以这些语句无效

  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

在这些陈述中更准确地说,试图从 --- 类型的对象构建一个类型为 std::pair<std::string, int> std::pair<char, int> 对象。这要求有一个 std::string 类的构造函数,其参数类型为 char 。但是没有这样的构造函数。

至于这些说法

  freq[0] = std::make_pair(*it,0);        //This is fine
  freq[0] = std::make_pair('S',0);        //This is fine

然后使用 std::basic_string 类的赋值运算符。该类有一个重载赋值运算符,它接受 char 类型的对象。

 basic_string& operator=(charT c);

所以这些说法是正确的。

考虑以下示例

#include <iostream>
#include <string>
#include <utility>

int main()
{
    std::pair<std::string, int> p1 = { "a", 1 };
    std::pair<char, int> p2 = { 'B', 2 };

    p1 = p2;

    std::cout << p1.first << '\t' << p1.second << std::endl;

    return 0;
}

输出是

B   2

由于类 std::pair 具有模板赋值运算符,而类 std::string 又具有具有 char 类型参数的赋值运算符,则此代码编译成功。

例如,如果您要写

std::pair<std::string, int> p1 = std::make_pair( 'a', 1 );

代替

    std::pair<std::string, int> p1 = { "a", 1 };

you would get an error because there is no conversion from std::pair<char, int> to std::pair<std::string, int> because there is no constructor from char to std::string .

原文由 Vlad from Moscow 发布,翻译遵循 CC BY-SA 3.0 许可协议

问题是您正在尝试从单个字符构造 std::stringstd::string 没有这样的构造函数。

原文由 PaulMcKenzie 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题