c++ - C++ 中的 set<pair> 和 map 有什么区别?

标签 c++ data-structures stl map set

有两种方法可以在 C++ STL 中轻松创建键值属性:映射和对集。例如,我可能有

map<key_class,value_class>

set<pair<key_class,value_class> >

在算法复杂度和编码风格方面,这些用法有什么区别?

最佳答案

它们在语义上是不同的。考虑:

#include <set>
#include <map>
#include <utility>
#include <iostream>

using namespace std;

int main() {
  pair<int, int> p1(1, 1);
  pair<int, int> p2(1, 2);
  set< pair<int, int> > s;
  s.insert(p1);
  s.insert(p2);
  map<int, int> m;
  m.insert(p1);
  m.insert(p2);
  cout << "Set size = " << s.size() << endl;
  cout << "Map size = " << m.size() << endl;
}

http://ideone.com/cZ8Vjr

输出:

Set size = 2
Map size = 1

关于c++ - C++ 中的 set<pair> 和 map 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3248554/

相关文章:

c++ - 控制台崩溃输出指针数组和迭代 C++

java - 如何在运行时传递数组的大小?

c - 为什么在将反向排序数组作为输入时出现段错误?

c++ - 被 const 逼入绝境:std::map::find() const 重载

c++ - 我不能使用 TCHAR[] 找到映射容器 TCHAR* 的键值吗?

c++ - 带有额外可选模板参数的标准库容器?

c++ - 在 centOS7 上安装 ceres-solver 并让 helloworld.cc 工作

c++ - 在 Windows 上的 Netbeans 中设置 Mysql C++ 连接器

c++ - 为什么没有通过 ""比较检查空字符串的优化?

java - 实现特定类的 LinkedList,而不是泛型类型