c++ - 通过->语法c++从指针访问函数

标签 c++

<分区>

我在类函数中工作:

void Planner::CellSort()
{
    vector<vector<int>> *pointer_to_open = &openlist;
    sort(pointer_to_open->begin(), pointer_to_open->end(), Compare);
}

当我尝试编译它时,出现以下错误:

error: must use '.*' or '->*' to call pointer-to-member function

但是当我尝试以下编译时就好了:

sort((&openlist)->begin(), (&openlist)->end(), Compare);

两者实际上不是在做同样的事情吗?或者这两种方法之间有什么区别。

这是我的比较函数:

bool Planner::Compare(const vector<int> a, const vector<int> b)
{
    int f1 = a[2] + a[3]; // f1 = g1 + h1
    int f2 = b[2] + b[3]; // f2 = g2 + h2
    return f1 > f2;
}

谢谢。

最佳答案

考虑 vector<vector<int>> *pointer_to_open = &openlist;

所以,这里pointer_to_open的地址是openlist .所以,如果做 *pointer_to_open , 它将指向 openlist 的值, 不是 pointer_to_open (因为它有 openlist 的地址)。

您正在使用:

pointer_to_open而不是 *pointer_to_open

考虑 thisthis关于指针和 vector 的文章。

你可以做什么:

void Planner::CellSort()
{
    vector<vector<int>> *pointer_to_open = &openlist;
    sort(*pointer_to_open->begin(), *pointer_to_open->end(), Compare);
}

它应该和使用 &openlist 一样好用

关于c++ - 通过->语法c++从指针访问函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55979970/

相关文章:

c++ - 将外部库添加到 CMakeList.txt c++

c++ - 哪个更快/首选 : memset or for loop to zero out an array of doubles?

c++ - 在 OS X (C++) 中设置 Eclipse 错误 : launch failed, 二进制文件未找到?

c++ - 如何最有效地修改 R/G/B 值?

c++ - boost::asio 文件发送

c++ - 是否可以将函数(指针?)保存到对象中?

c++ - 动画持续时间不正确

c++ - 如何在同一个立体窗口中并排显示 2 个网络摄像头视频?

c++ - 带有成员初始化的元组初始化

c++ - 复制所有父类(super class)构造函数