gpt4 book ai didi

c++ - 从一个 vector 中减去另一个 vector

转载 作者:行者123 更新时间:2023-11-28 07:49:15 24 4
gpt4 key购买 nike

我组织了两个结构 vector 。现在我需要从 points 中删除 chosen 中的内容。

#include <StdAfx.h>;
#include <iostream>;
#include <vector>;

using namespace std;
struct SPoint
{
int id;
int X;
int Y;
};

vector<SPoint> points;
vector<SPoint> chosen;

void print_vect(const vector<SPoint> & vect)
{
for (int i = 0; i < vect.size(); ++i)
{
cout << vect[i].id << " (" << vect[i].X << "," << vect[i].Y << ")"<<endl;
}

cout << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
SPoint temp;
for (int i = 0; i < 10; i++)
{
temp.id = i;
temp.X = i;
temp.Y = i;
points.push_back(temp);
}

for (int i = 5; i < 10; i++)
{
temp.id = i;
temp.X = i;
temp.Y = i;
chosen.push_back(temp);
}

cout << "Points:" << endl;
print_vect(points);
cout << endl << endl;

cout << "Chosen:" << endl;
print_vect(chosen);

system("pause");

return 0;
}

好像有set_difference函数。但是调试器告诉我,我没有“<”方法。它讲述了这样的事情:

error C2784: 'bool std::operator <(const std::move_iterator<_RanIt> &,const std::move_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::move_iterator<_RanIt> &' from 'SPoint

我学习 C++ 过程式编程。而且我不知道如何使用这种方法。在我看来,用“<”在这里做任何事情都是不可能的。

你能帮我执行减法吗?

最佳答案

是的,你猜对了。 std::set_difference 函数需要 < 运算符才能运行。它使用它来检查相等性作为 (!a

The comparison to check for equivalence of values, uses either
operator< for the first version, or comp for the second, in order to
test this; The value of an element, a, is equivalent to another one,
b, when (!a<b && !b<a) or (!comp(a,b) && !comp(b,a)).

您需要做的就是添加如下所示的函数

bool operator<(const SPoint& p1, const SPoint&p2){
return p1.id <p2.id;
}

假设您的 id 字段是一个唯一字段。现在您将能够使用 std::set_difference 函数。这通过它们的 id 字段比较两个 SPoint 变量。

请注意,两个范围都需要排序才能正常工作。

关于c++ - 从一个 vector 中减去另一个 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14190199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com