问题描述
我有一个向量,其中我保存对象。我需要转换它设置。我一直在阅读关于集,但我仍然有几个问题:
I have a vector, in which I save objects. I need to convert it to set. I have been reading about set, but I still have a couple of questions:
如何正确初始化它?老实说,一些教程说,它很好,初始化它像 set< ObjectName>某些
。其他人说你还需要一个迭代器,如 set< Iterator,ObjectName>某些
。
How to correctly initialize it? Honestly, some tutorials say it is fine to initialize it like set<ObjectName> something
. Others say that you need an iterator there too, like set<Iterator, ObjectName> something
.
如何正确插入。再次,是否只需写 something.insert(object)
就够了?
How to insert them correctly. Again, is it enough to just write something.insert(object)
and that's all?
集合中的对象(例如对象,其中有名称变量,等于ben)?
How to get specific object (for example object, which has name variable in it, which is equal to "ben") from set?
PS我有转换矢量它自我作为一个集合(a.k.a.我必须使用集而不是矢量)。只有设置可以在我的代码。
P.S. I have convert vector it self to be as a set (a.k.a. I have to use set rather then vector). Only set can be in my code.
推荐答案
你没有告诉我们很多关于你的对象,像这样:
You haven't told us much about your objects, but suppose you have a class like this:
class Thing
{
public:
int n;
double x;
string name;
};
你想把一些东西放入一个集合,所以你试试这个:
You want to put some Things into a set, so you try this:
Thing A;
set<Thing> S;
S.insert(A);
这会失败,因为集合被排序,并且没有办法对事物进行排序,因为没有办法比较其中两个。您必须提供 运营商
:
This fails, because sets are sorted, and there's no way to sort Things, because there's no way to compare two of them. You must provide either an operator<
:
class Thing
{
public:
int n;
double x;
string name;
bool operator<(const Thing &Other) const;
};
bool Thing::operator<(const Thing &Other) const
{
return(Other.n<n);
}
...
set<Thing> S;
或比较函数对象:
class Thing
{
public:
int n;
double x;
string name;
};
struct ltThing
{
bool operator()(const Thing &T1, const Thing &T2) const
{
return(T1.x < T2.x);
}
};
...
set<Thing, ltThing> S;
要找到名字为ben的Thing,可以遍历集合,如果你更具体地告诉我们你想做什么,真的很有帮助。
To find the Thing whose name is "ben", you can iterate over the set, but it would really help if you told us more specifically what you want to do.
这篇关于如何转换矢量集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!