std :: set vs vector或maps的优点

时间:2013-04-29 19:30:46

标签: c++ stdvector stdmap stdset

这可能是一个愚蠢的问题,我对C ++和编程很新。 我想了解几个STL容器的使用,考虑到这一点,我想知道使用std :: set vs使用矢量或地图的优点是什么? 我似乎无法找到这个问题的明确答案。我注意到集合使用地图,但为什么不总是使用地图或总是使用集合。而是提供了两个非常相似的容器。 提前谢谢。

5 个答案:

答案 0 :(得分:58)

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

答案 1 :(得分:23)

一个集合可用于存储“typeOfFruits”

的枚举等唯一内容
std::set<typeOfFruits> fruits;   
fruits.insert (banana);
fruits.insert (apple);
fruits.insert (pineapple);

//it's fast to know if my store sells a type of fruit.
if (fruits.find (pear) == fruits.end())
{ std::cout<<"i don't have pear"; }

地图可用于存储唯一的内容,以及“值”

std::map<typeOfFruits, double /*unit price*/> fruits;  
fruits[banana] = 1.05;
fruits[apple] = 0.85;
fruits[pineapple] = 3.05;
//repeating pineapple will replace the old price (value)
fruits[pineapple] = 3.35;

//it's fast to know how much a fruit costs.
std::map<typeOfFruits, double /*unit price*/> itr = fruits.find(pineapple);
if (itr != fruits.end())
{ std::cout<<"pineapples costs: $" <<itr->second; }

向量可用于存储序列有序的内容(push_back())。 想象一下你在收银台扫描你的水果,程序跟踪这个扫描。

std::vector<typeOfFruits> fruits;
fruits.push_back(apple);
fruits.push_back(apple); 
fruits.push_back(apple);
fruits.push_back(banana);
fruits.push_back(banana);
fruits.push_back(pineapple);
//i scanned 3 apples, 2 bananas and 1 pineapple.

答案 2 :(得分:3)

  • vector在容器后面的插入和删除速度更快。您可以通过运算符[]。
  • 访问元素
  • dequeuevector类似,但它具有正面插入和删除功能。
  • set只有密钥而mappair。这两个容器在容器中间插入和删除的速度更快。您还可以使用STL算法通过find访问元素。

答案 3 :(得分:2)

No body has mentioned the facts that std::set is actually immutable. You should not change the value of any element in it. std::set does not track over changes so when you edit a element in it you go behind its back and are likely to change its inner ordering. This is a risky behavior. Therefore use std::map if you want to edit elements after you put them into the container. Make sure you use key to induce ordering and everything you need to change afterwards into value.

答案 4 :(得分:1)

归结为您的应用程序最需要的复杂性保证,包括插入,删除,检索等。我强烈建议 Scott Meyers的有效STL