如果我希望它忽略重复元素,应使用哪个 STL 容器?
我正在寻找一些 STL(但不是 boost)容器,在执行以下操作后,它将包含 2 个元素:“abc”和“xyz”:
std::XContainer<string> string_XContainer;
string_XContainer.push_back("abc");
string_XContainer.push_back("abc");
string_XContainer.push_back("xyz");
顺便说一句,我需要它只是为了调用 string_XContainer.size( ) 最后,获取唯一字符串的总数。那么也许我什至不需要容器,并且有一种更优雅的方法来做到这一点?
I am looking for some STL (but not boost) container, which after the following operations will contain 2 elements: "abc" and "xyz":
std::XContainer<string> string_XContainer;
string_XContainer.push_back("abc");
string_XContainer.push_back("abc");
string_XContainer.push_back("xyz");
By the way, I need it just in order to call string_XContainer.size()
in the end, to get the total number of unique strings. So maybe I don't even need a container, and there is a more elegant way of doing it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
std::set
就是你后。根据您定义的某个比较器函数进行比较,集合最多包含每个元素的一个实例。这将是获取唯一字符串数量的一种方法。从你的例子来看,字符串已经按顺序排列了?如果是这种情况,那么您可以创建一个数组(或其他一些简单的结构)并使用
std::unique
算法。std::set
is the one you are after. A set will contain at most one instance of each element, compared according to some comparator function you define.This would be one approach to get the number of unique strings. From your example, the strings were already in sorted order? If that's the case, then you could just create an array (or some other simple structure) and use the
std::unique
algorithm.