【发布时间】:2022-01-20 08:23:19
【问题描述】:
我正在尝试通过for 循环从std::vector<std::pair<std::string,std::string>> 打印数据。 MSVC 说我不能通过这个向量拨打电话。我也用std::vector<std::pair<int, int>> 尝试过,得到了同样的错误。我尝试在std::vector<int> 上使用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<std::function(void()), std::function(void())>可以使用p.first()作为函数。这不是first问题,而是is the type first holds invocable?问题。 -
@Elijay - 不是在 OP 的情况下,成员是
std::string。