【C++】map::erase 与 vector::erase 的返回值

C++中的map和vector的erase函数在删除元素后,会返回不同情况的迭代器。如果删除的不是最后一个元素,它们返回的是下一个元素的迭代器;若删除的是最后一个元素,则返回end()。直接解引用end()是不被允许的行为。
摘要由CSDN通过智能技术生成
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
#include<random>
#include<chrono>
using namespace std;
unsigned a[] = {
    11,12,13,14,15,16,17,18,19,20 };
map<unsigned, unsigned> m; vector<unsigned> v;
mt19937_64 re;
int main() {
   
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); re.seed(chrono::steady_clock::now().time_since_epoch().count());
	for (auto i : a) {
   
		m.emplace(make_pair(i, i)); v.emplace_back(i);
	}
	shuffle(a, a + 10, re);
	for (auto i : a) {
   
		auto j = m.erase(m.find(i));
		cout << "(j == m.end) == " << boolalpha << (j == m.end()) << endl;
		cout << "m.crbegin()->first == " << m.crbegin()->first << endl;
		cout << "Erased term = " << i << ", m.size = " << m.size() << ", following term = " << j->first << endl;
		cout << endl;
	}
	cout << endl;
	for (auto i : a) {
   
		auto j = v.erase(find(v.cbegin(), v.cend(), i));
		cout << "(j == v.end) == " << boolalpha << (j == v.end()) << endl;
		cout << 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值