C++中的struct(結構體)是一種自定義的數據類型,它可以將不同類型的數據組合在一起
struct Person {
string name;
int age;
char gender;
};
struct Data {
int id;
float value;
};
// 寫入文件
Data data = {1, 3.14f};
ofstream outFile("data.bin", ios::binary);
outFile.write(reinterpret_cast<char*>(&data), sizeof(Data));
// 讀取文件
Data readData;
ifstream inFile("data.bin", ios::binary);
inFile.read(reinterpret_cast<char*>(&readData), sizeof(Data));
struct Student {
string name;
int score;
};
bool compare(const Student &a, const Student &b) {
return a.score > b.score;
}
Student students[] = {{"Alice", 90}, {"Bob", 85}, {"Cathy", 95}};
sort(students, students + sizeof(students) / sizeof(Student), compare);
struct Point {
int x;
int y;
};
unordered_map<Point, string> pointMap;
pointMap[{3, 4}] = "Pythagorean theorem";
這些只是結構體數組在數據結構中的一些應用場景,實際上,結構體可以根據需求進行更多的定制和組合。