如何将矢量转换为集合?
我有一个向量,我在其中保存对象.我需要将其转换为设置.我一直在阅读关于集合的内容,但我仍有几个问题:
I have a vector, in which I save objects. I need to convert it to set. I have been reading about sets, 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, likeset<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 a specific object (for example, an object which has a named variable in it, which is equal to "ben") from the set?
我必须将向量本身转换为一个集合(也就是我必须使用集合而不是向量).
I have to convert the vector itself to be a set (a.k.a. I have to use a set rather than a vector).
推荐答案
你没有告诉我们太多关于你的对象,但是假设你有一个这样的类:
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);
这失败了,因为集合是排序的,没有办法对事物进行排序,因为没有办法比较它们中的两个.您必须提供 operator<
:
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"的事物,您可以遍历集合,但如果您更具体地告诉我们您想要做什么,这将非常有帮助.
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.
相关文章