哈希表,有序表和比较器

一,补充

1,new分配返回的是地址,即使储存的值相同,赋值对象也不想等

#include<string>
#include<iostream>

using namespace std;

int main()
{
	string* str1 = new string("hello");
	string* str2 = new string("hello");
	if (*str1 == *str2) cout << "Yes";
	else cout << "No";
	cout << endl;
	if (str1 == str2) cout << "Yes";
	else cout << "No";
	return 0;
}

二,概论

三,hashset

1,补充

在 C++ 中,unordered_set 的 erase 函数删除的是集合中的元素,并且在删除时会自动释放与该元素关联的内存,但是是否完全释放内存取决于元素的类型和内存管理方式。

对于 unordered_set<string*> 类型

在你的例子中,unordered_set<string*> 存储的是指针(string*)。当你调用 erase 删除一个指针元素时,unordered_set 只会从集合中删除该指针本身(即从容器中移除指向该字符串的指针),并不会自动释放该指针所指向的字符串的内存。

具体来说:

  1. erase 会移除指针元素,这意味着 unordered_set 不再持有该指针。
  2. 然而,指针指向的字符串(new string("hello"))依然会存在,除非你手动删除(例如使用 delete)。

删除后set集合里面就没有存储对应元素的空间了。

四,hashmap和pair结构

五,比较器或比较函数

使用案例:
 

#include<iostream>
#include<algorithm>

using namespace std;

struct Student
{
	int age;
	const char* name;
	Student(int x, const char* ch) : age(x), name(ch) {};
};

bool compare(Student* a, Student* b)
{
	return a->age < b->age;
}

int main()
{
	const char* arr[] = { "jack","helen","mark","alice","ducker" };
	Student* arr1[5];
	for (int i = 0; i < 5; i++)
	{
		Student* st = new Student(10 - i, arr[i]);
		arr1[i] = st;
	}

	for (int i = 0; i < 5; i++)
	{
		cout << arr1[i]->name << " ";
	}
	cout << endl;
	sort(begin(arr1), end(arr1), compare);
	for (int i = 0; i < 5; i++)
	{
		cout << arr1[i]->name << " ";
	}

	return 0;
}

使用lamda函数替代比较函数

代码

sort(begin(arr1), end(arr1), [](const Student* a, const Student* b) ->bool { return a->age < b->age;});

迭代器与指针间的区别

string的成员函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值