划分指针向量时的谓词语法 (C++)

发布于 2024-08-08 16:24:46 字数 989 浏览 7 评论 0原文

我有一个指向对象的指针向量。我想根据成员函数报告的属性从此向量中删除对象。

我正在尝试遵循我发现的一个很好的示例,了解如何从向量中删除某些指针(及其关联的对象)。基本思想是对向量进行分区,删除所选对象,然后删除指向这些对象的指针。下面是示例(来自Dr. Dobbs):

vector<Object *> v ;

v.push_back( new Object( ... ) ) ;
...
vector<Object *>::iterator last =
partition( v.begin(), v.end(), not1(predicate()) ) ;
for( vector<Object *>::iterator i = last ; i != v.end() ; ++i )
{
  delete *i ;
}
v.erase( last, v.end() ) ;

我对正确的语法感到困惑谓词。我的对象属于 Strain 类,我的向量是向量<应变*>活菌株。谓词应该是 Strain 成员函数 isExtinct()。以下不起作用:

 vector< Strain * >::iterator last = partition( liveStrains.begin(), liveStrains.end(), not1(std::mem_fun_ref(&Strain::isExtinct)) );

我可以看到我正在尝试调用指向对象的指针而不是对象本身的成员函数。为了解决这个问题,尝试更改 &到*(我显然是一个新手),我尝试为类Simulation创建一个成员函数,该函数在成员函数中进行liveStrains更新。我不确定是否值得深入探讨不起作用的细节。我对可用的语法选项感到严重困惑,或者我想做的事情是否被允许。

预先感谢您的任何帮助。

I have a vector of pointers to objects. I'd like to remove objects from this vector according to an attribute that's reported by a member function.

I'm trying to follow a nice example I found on how to delete certain pointers (and their associated objects) from the vector. The basic idea is to partition the vector, delete the chosen objects, and then delete the pointers to those objects. Below is the example (from Dr. Dobbs):

vector<Object *> v ;

v.push_back( new Object( ... ) ) ;
...
vector<Object *>::iterator last =
partition( v.begin(), v.end(), not1(predicate()) ) ;
for( vector<Object *>::iterator i = last ; i != v.end() ; ++i )
{
  delete *i ;
}
v.erase( last, v.end() ) ;

I'm stumped on the proper syntax for the predicate. My objects are of class Strain, and my vector is vector< Strain * > liveStrains. The predicate should be the Strain member function isExtinct(). The following doesn't work:

 vector< Strain * >::iterator last = partition( liveStrains.begin(), liveStrains.end(), not1(std::mem_fun_ref(&Strain::isExtinct)) );

I can see that I am trying to invoke a member function on a pointer to the object rather than the object itself. To get around this, tried changing the & to * (I'm obviously a newbie), and I tried creating a member function for the class Simulation that does the liveStrains updating in a member function. I'm not sure it's worth going into the details of what didn't work. I'm severely confused by the syntactical options available, or if what I'm trying to do is even allowed.

Thanks in advance for any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

荒岛晴空 2024-08-15 16:24:46

解决方案是使用 std::mem_fun,它是为指针而设计的对象,而不是 std::mem_fun_ref。

The solution is to use std::mem_fun, which is made for pointers to objects, rather than std::mem_fun_ref.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文