21xrx.com
2024-09-20 05:32:45 Friday
登录
文章检索 我的文章 写文章
C++集合映射
2023-07-01 16:19:47 深夜i     --     --
C++ STL 数据结构 映射表 集合操作 算法实现

在C++中,集合和映射是两个常用的数据结构。它们被广泛用于存储和管理数据,特别是在算法和程序设计中。在这篇文章中,我们将介绍C++中集合和映射的概念、实现和用法。

集合是一种无序的,没有重复元素的数据结构。在C++中,集合通常用STL库中的set类实现。set是一个红黑树的实现,能够快速地搜索、插入、删除元素,还支持集合之间的交集、并集和差集等运算。

例如,下面是一些使用set的示例代码:


#include <iostream>

#include <set>

using namespace std;

int main() {

  set<int> myset;

  myset.insert(3);

  myset.insert(9);

  myset.insert(6);

  myset.insert(1);

  set<int>::iterator it;

  for (it = myset.begin(); it != myset.end(); it++) {

    cout << *it << " "; //输出1 3 6 9

  }

  myset.erase(3); //删除3

  if (myset.find(6) != myset.end())

    cout << "6 is in the set." << endl;

  

  if (myset.count(9) > 0) {

    cout << "There is " << myset.count(9) << " 9 in the set." << endl;

  }

  return 0;

}

该代码创建了一个set并插入了一些整数。通过迭代器访问集合中的元素,并且可以使用erase函数删除一个元素。可以使用find函数查找元素是否包含在集合中,也可以使用count函数查找元素的出现次数。

与集合不同,映射是一种键值对的数据结构,也称为字典或关联数组。在C++中,映射通常使用STL库中的map类实现。map是一个有序的关联数组,可以按任何键顺序进行访问,也支持插入删除和查找元素。

下面是一些使用map的示例代码:


#include <iostream>

#include <map>

using namespace std;

int main() {

  map<string, int> mymap;

  mymap["apple"] = 10;

  mymap["banana"] = 5;

  mymap["orange"] = 15;

  mymap["grape"] = 20;

  map<string, int>::iterator it;

  for (it = mymap.begin(); it != mymap.end(); it++)

    cout << it->first << " " << it->second << endl;

  

  mymap.erase("orange");

  if (mymap.count("apple") > 0) {

    cout << "There are " << mymap["apple"] << " apples in the map." << endl;

  }

  return 0;

}

该代码创建了一个map并插入了一些键值对。通过迭代器遍历map中的元素,并且可以使用erase函数删除某个键值对。可以使用count函数查找特定键的出现次数,也可以直接通过[]运算符访问键对应的值。

总结

C++集合和映射是两个常用的数据结构,它们在算法和程序设计中发挥着重要作用。通过STL库中的set和map类实现,可以快速地进行元素的插入、删除、查找和操作。在实际的编程过程中,可以根据需要选择适合自己的数据结构来存储和管理数据。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复