c++ vector 结构体
时间: 2023-10-21 12:04:16 浏览: 52
C++ 中的 vector 是一个动态数组容器,可以存储大量的数据。它通过动态地分配内存空间来自动处理大小调整。结构体是一种用户定义的数据类型,它可以组合不同类型的数据成员。它是一种非常有用的工具,可以方便程序员对数据进行处理和管理。结构体可以包含多个成员,每个成员可以是不同的类型,如 int、float、char、double 等。通过使用结构体和 vector ,可以轻松地管理和操作复杂的数据结构。
相关问题
c++ vector 结构体排序 去重复
对于结构体类型的 vector,可以使用 sort 函数进行排序,使用 unique 函数进行去重。
下面是一个例子,假设有一个结构体类型为 Person:
```c++
struct Person {
string name;
int age;
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
};
```
将 Person 结构体类型的 vector 进行排序和去重的代码如下:
```c++
vector<Person> persons = {{"Alice", 22}, {"Bob", 20}, {"Alice", 22}, {"Charlie", 21}};
// 按照年龄从小到大排序
sort(persons.begin(), persons.end(), [](const Person& a, const Person& b) {
return a.age < b.age;
});
// 去重复
auto last = unique(persons.begin(), persons.end());
persons.erase(last, persons.end());
```
上述代码中,使用了一个 lambda 表达式作为 sort 函数的第三个参数,该 lambda 表达式的功能是按照年龄从小到大进行排序。另外,unique 函数会返回去重后 vector 的最后一个元素的迭代器,可以使用 erase 函数将 vector 中多余的元素删除。
用C++写vector结构体排序
下面是一个使用C++的STL库中的vector结构体进行排序的示例代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Person {
string name;
int age;
};
bool compareByAge(const Person &a, const Person &b) {
return a.age < b.age;
}
int main() {
vector<Person> people {
{"Alice", 25},
{"Bob", 30},
{"Charlie", 20},
{"David", 35},
{"Eve", 27}
};
sort(people.begin(), people.end(), compareByAge);
for (const auto &person : people) {
cout << person.name << " " << person.age << endl;
}
return 0;
}
```
在上面的代码中,我们首先定义了一个名为`Person`的结构体,其中包含两个成员变量:`name`和`age`。然后,我们创建了一个`vector`类型的`people`对象,并向其中添加了一些`Person`对象。接下来,我们使用`sort`函数来对`people`进行排序,该函数会根据`compareByAge`函数的返回值来进行排序。最后,我们遍历`people`并输出每个`Person`对象的`name`和`age`属性。