【问题标题】:Why can't I access a std::vector<std::pair<std::string, std::string>> through vec[i].first()?为什么我不能通过 vec[i].first() 访问 std::vector<std::pair<std::string, std::string>>?
【发布时间】:2022-01-20 08:23:19
【问题描述】:

我正在尝试通过for 循环从std::vector&lt;std::pair&lt;std::string,std::string&gt;&gt; 打印数据。 MSVC 说我不能通过这个向量拨打电话。我也用std::vector&lt;std::pair&lt;int, int&gt;&gt; 尝试过,得到了同样的错误。我尝试在std::vector&lt;int&gt; 上使用for 循环进行迭代,效果很好。我还没有尝试过其他编译器。

示例代码

    std::vector<std::pair<std::string, std::string>> header_data = get_png_header_data(file_contents);

    for (unsigned int i = 0; i < header_data.size(); i++)
    {
        std::cout << header_data[i].first(); //throws an error on this line "call of an object of a class type without an appropriate operator() or conversion functions to pointer-to-function type
    }

我希望有一种替代方法来访问我的向量或我可以使用的其他存储类型。

谢谢:)

【问题讨论】:

  • 查看accepted answer 的使用情况
  • .first 是 pair 对象的数据成员,而不是函数。
  • header_data[i].first()header_data[i].first 视为一个函数(或带有operator() 的函数对象),并在没有参数的情况下调用它。该错误是因为 std::pair 的成员 first 不能像函数一样使用。删除()
  • @Peter • std::pair&lt;std::function(void()), std::function(void())&gt; 可以使用p.first() 作为函数。这不是first 问题,而是is the type first holds invocable? 问题。
  • @Elijay - 不是在 OP 的情况下,成员是 std::string

标签: c++ stdvector


【解决方案1】:

您的std::pair 基本上是(在某种意义上):

    struct std::pair {
        std::string first;
        std::string second;
    };

std::pairs 就是这样。 firstsecond 是普通的类成员,而不是方法/函数。现在您可以很容易地看到发生了什么:.first() 尝试调用 first() 运算符重载。显然,std::strings 没有这样的重载。这就是你的 C++ 编译器的错误信息告诉你的。如果您重新阅读编译器的错误消息,它现在变得非常清晰。

你显然是想写std::cout &lt;&lt; header_data[i].first;

【讨论】:

  • 我觉得自己很笨。感谢您花时间回答我的问题,我会在 7 分钟内接受。
  • C++ 是当今世界上最复杂、最难学习的通用编程语言。你不是第一个,也不会是最后一个被编译器的错误信息弄糊涂的人。每个人都会在某个时候经历那个阶段。这是完全正常的。您通常会期望一条错误消息会说“first is not a function”之类的内容。但是 C++ 实在是太复杂了。 first 可能是具有完全可用的 () 重载的类,因此在这种情况下,您尝试执行的操作实际上可能会编译。
  • 每个人都会在某个时候经历那个阶段。 这个阶段从 C++ 编程的第一天开始,一直持续到最后一天。即使是我的同事和在 C++ 方面非常有经验的前同事也会犯这类错误,例如 Alex Stepanov 和 Scott Meyers。
猜你喜欢
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 1970-01-01
  • 2020-02-01
  • 1970-01-01
  • 2011-06-04
相关资源
最近更新 更多