C++set容器pair对组创建

C++set容器pair对组创建

功能描述:

  • 成对出现的数据,利用对组可以返回两个数据
#include <iostream>
#include <string>
using namespace std;

void test01()
{
	pair<string, int>p(string("Tom"), 20);
	cout << "姓名: " << p.first << " 年龄: " << p.second << endl;

	pair<string, int> p2 = make_pair("Jerry", 10);
	cout << "姓名: " << p2.first << " 年龄:" << p2.second << endl;
}
int main()
{
	test01();
	return 0;
}

C++set容器pair对组创建

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中,可以使用迭代器来遍历set容器和map容器。下面是遍历这两种容器的示例代码: 遍历set容器: ```cpp std::set<int> mySet = {1, 2, 3, 4, 5}; // 使用迭代器遍历set容器 for (std::set<int>::iterator it = mySet.begin(); it != mySet.end(); ++it) { int element = *it; // 获取当前元素的值 // 执行操作,例如打印或处理元素 } ``` 遍历map容器: ```cpp std::map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "cherry"}}; // 使用迭代器遍历map容器 for (std::map<int, std::string>::iterator it = myMap.begin(); it != myMap.end(); ++it) { int key = it->first; // 获取当前键的值 std::string value = it->second; // 获取当前值的值 // 执行操作,例如打印或处理键值对 } ``` 另外,C++11引入了范围-based for循环,也可以用于遍历set容器和map容器: 遍历set容器: ```cpp std::set<int> mySet = {1, 2, 3, 4, 5}; // 使用范围-based for循环遍历set容器 for (const auto& element : mySet) { // 执行操作,例如打印或处理元素 } ``` 遍历map容器: ```cpp std::map<int, std::string> myMap = {{1, "apple"}, {2, "banana"}, {3, "cherry"}}; // 使用范围-based for循环遍历map容器 for (const auto& pair : myMap) { int key = pair.first; // 获取当前键的值 std::string value = pair.second; // 获取当前值的值 // 执行操作,例如打印或处理键值对 } ``` 请注意,在遍历map容器时,使用`pair.first`获取键,使用`pair.second`获取值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值