c++ vector 装结构体struct类型变量, 结构体成员变量的值
时间: 2023-07-08 09:50:19 浏览: 201
在 C++ 中,可以使用 vector 容器来存储结构体类型的变量。假设我们有以下结构体定义:
```
struct Student {
int id;
std::string name;
};
```
可以使用 vector 容器来存储结构体类型的变量:
```
std::vector<Student> students;
// 添加学生
Student new_student = {1, "Tom"};
students.push_back(new_student);
// 修改学生姓名
students[0].name = "Jerry";
```
在使用 vector 容器时,可以直接访问结构体成员变量,并进行修改。需要注意以下几点:
- 可以使用 push_back 函数向 vector 容器中添加元素。
- 可以使用下标运算符 [] 访问 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`属性。
c++对vector结构体数组进行排序
可以使用`std::sort()`函数对`vector`结构体数组进行排序。以下是一个示例代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
struct MyStruct {
int value;
// 其他成员变量...
};
bool compare(const MyStruct& a, const MyStruct& b) {
return a.value < b.value;
}
int main() {
std::vector<MyStruct> myVector;
// 将需要排序的结构体对象添加到vector中
std::sort(myVector.begin(), myVector.end(), compare);
for (const auto& item : myVector) {
// 输出排序后的结果
std::cout << item.value << " ";
}
return 0;
}
```
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044947.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)