一,补充
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
只会从集合中删除该指针本身(即从容器中移除指向该字符串的指针),并不会自动释放该指针所指向的字符串的内存。
具体来说:
erase
会移除指针元素,这意味着unordered_set
不再持有该指针。- 然而,指针指向的字符串(
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;});