如果我希望它忽略重复元素,应使用哪个 STL 容器?

发布于 2024-08-14 06:42:35 字数 344 浏览 0 评论 0原文

我正在寻找一些 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风吹短裙飘 2024-08-21 06:42:35

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文