如何解决带有向量和类的函数指针
为了做作业,我学习了函数指针和lambda函数。
我创建了一个包含宽度和长度并计算面积的类 Rectangle
。
问题之一是创建一个类 MyVector
,它是 stl 向量的派生类,并包含名为 func 的函数,该函数接受一个布尔函数作为参数,如果向量中的至少一个元素是答案,则返回 true否则,将返回 false。(我将这个布尔函数称为 cmp)
主要是,我必须检查是否至少一个矩形的面积大于 50,如果是,则显示所有矩形。
这个指针函数我不是很懂怎么用,能不能通过我的例子帮我理解一下
矩形类:
#pragma once
#include <iostream>
using namespace std;
class Rectangle
{
private:
int width;
int length;
public:
Rectangle(int x,int y) : width(x),length(y) {};
int area() { width* length; }
friend ostream& operator<<(ostream& os,const Rectangle& r);
};
ostream& operator<<(ostream& os,const Rectangle& r)
{
os << r.width << " " << r.length << endl;
return os;
}
MyVector 类:
#include <iostream>
#include <vector>
#include <algorithm>
#include "Rectangle.h"
using namespace std;
template <class T>
class MyVector : public vector<T>
{
public:
bool func(bool(*cmp)); //This is a function I create,I don't kNow how to use cmp function to compare area
};
template <class T>
bool MyVector<T>::func(bool(*cmp))
{
MyVector<T>::iterator it;
for (it = MyVector.begin(),it < MyVector.end(),it++)
if (func(*it))
return true;
return false;
}
#include <iostream>
#include "Rectangle.h"
#include "MyVector.h"
using namespace std;
int main()
{
MyVector<Rectangle> Myvec;
Myvec.push_back(Rectangle(2,4));
Myvec.push_back(Rectangle(4,8));
Myvec.push_back(Rectangle(8,16));
Myvec.push_back(Rectangle(16,32));
Myvec.push_back(Rectangle(32,64));
Myvec.push_back(Rectangle(64,128));
if (Myvec.func(/*Here I have to complete*/)
//If func function return true print all vector element
);
return 0;
}
解决方法
您需要对 func() 的实现进行一些更改:
template <class T>
bool MyVector<T>::func(bool(*cmp)(const T&))
{
typename MyVector<T>::iterator it;
for (it = this->begin(); it < this->end(); it++)
if (cmp(*it))
return true;
return false;
}
你所拥有的和这个之间的主要区别是:
- 传入的函数指针将接受类型为
const T&
的单个参数 - 迭代发生在
this->begin()
到this->end()
(您在那里不会编译的内容) - 使用
cmp(*it)
代替func(*it)
然后你可以在主函数中实际使用它,例如:
bool larger_than_50_area(const Rectangle& r) {
return r.area() > 50;
}
int main()
{
MyVector<Rectangle> Myvec;
...
if (Myvec.func(larger_than_50_area)) {
...
}
return 0;
}
如果有帮助,请告诉我!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。