std :: set与矢量或地图的优势 [英] advantages of std::set vs vectors or maps

查看:102
本文介绍了std :: set与矢量或地图的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,我对C ++和一般编程还是很陌生. 我想了解几个STL容器的使用,并牢记这一点,我想知道使用std :: set与使用矢量或地图相比有什么优势? 我似乎找不到这个问题的明确答案.我注意到集合使用地图,但是为什么不总是使用地图或总是使用集合呢?而是提供了2个非常相似的容器. 预先感谢.

This may be a stupid question, I am quite new to C++ and programming in general. I wish to understand the use of several STL containers and with that in mind, I was wondering what the advantages are of using std::set vs for example using vectors or maps? I can't seem to find an explicit answer to this question. I noticed that sets use maps, but then why not always use maps or always use sets. Instead 2 quite similar containers are provided. Thanks in advance.

推荐答案

std::setstd::map都是关联容器.区别在于std::set仅包含密钥,而在std::map中具有关联的值.一个选择另一个主要取决于当前的任务.如果要构建一个文本中出现的所有单词的字典,可以使用std::set<std::string>,但是如果您还想计算每个单词出现的次数(即,将一个值与键相关联),则可以需要一个std::map<std::string,int>.如果不需要关联该计数,则不必使用不必要的int.

Both std::set and std::map are associative containers. The difference is that std::sets contain only the key, while in std::map there is an associated value. Choosing one over the other depends mainly on what the task at hand is. If you want to build a dictionary of all the words that appear in a text, you could use a std::set<std::string>, but if you also want to count how many times each word appeared (i.e. associate a value to the key) then you would need an std::map<std::string,int>. If you don't need to associate that count, it does not make sense to have the int that is unnecessary.

这篇关于std :: set与矢量或地图的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆