我正在尝试创建一个函数,如果一个元素在向量中,则返回 true/false,但我收到错误
I am trying to make a function with that returns true/false if an element is in the vector but I am getting an error?
我正在尝试使用 STL 在 C++ 中实现一个函数,该函数接受一个对象和一个对象向量,如果向量包含对象,则返回 true,否则为 false。以下是函数的实现:
bool belongs(vertex V, std::vector<vertex> &array)
{
std::vector<vertex>::iterator it;
it = find(array.begin(), array.end(), V);
if(it != array.end())
{
return true;
}
else
{
return false;
}
}
但是,我收到此错误:
invalid operands to binary expression ('vertex' and 'const vertex')
if (*__first == __value_)
我能做什么?我对使用面向对象编程的STL编程有点陌生,所以等待您的帮助。
主要问题是没有为顶点类型定义operator==
(find
需要顶点类型来确定 2 个vertex
实例是否相同)。您可以按如下方式定义一个:
#include <iomanip>
#include <iostream>
#include <vector>
#include <algorithm>
struct vertex
{
float a, b;
bool operator==(const vertex& o) const // <-- This method is what find is looking for
{
return a == o.a && b == o.b;
}
};
bool belongs(vertex V, const std::vector<vertex>& array)
{
return find(array.begin(), array.end(), V) != array.end();
}
int main()
{
std::vector<vertex> v = { { 1, 2 }, { 3, 4 } };
std::cout << std::boolalpha << belongs({ 4, 5 }, v);
return 0;
}
住在科里鲁
我还缩短了归属的实现,它更清楚地表明:
return x;
而不是:
if (x)
return true;
else
return false;
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 如何编写一个接受如下断言消息的自定义断言函数:assert(false) << "assertio
- 在一个作用域中推送五个对象指针,然后检查对象的布尔值是否为 false,会给出错误
- 给定一个大小的布尔数组,这都是真实的,我将如何仅使用递归将所有值设置为false
- 为什么在 sync_with_stdio(false) 之前使用 cin 为下一个 i/p 变量提供随机值
- 我正在尝试创建一个函数,如果一个元素在向量中,则返回 true/false,但我收到错误
- 单元测试一个变量的true和false
- 函数在另一个函数中调用时返回 false,而单个返回类型为 true
- 如何编写一个c++代码,使函数在初始参数为大写时返回true,如果不是,则返回false
- C++:为什么返回false的集合顺序的函子只允许向集合中添加一个元素
- 我们是否可以创建一个类似scanf的函数,当所有参数都填充时返回true,否则返回false,而不循环遍历所有变量?