C++ Struct
type
在程式語言裡,型別 (type) 定義了:
-
這個變數能儲存什麼樣的資料
-
資料在記憶體中的大小與格式
-
能對這個資料做什麼操作
e.g. int, string, float, char
自己定義一個type
如何自己創造一個新的type ?
(user-defined type)
Struct
struct type_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;
Syntax of struct
type_name: 你要創造的type
object_names: 在定義結構的同時,直接建立的一個或多個變數 (object)
Example
struct fruit {
int weight;
double price;
} ;
fruit apple;
fruit banana, melon;struct fruit {
int weight;
double price;
} apple, banana, melon;
Remark: struct結尾要加 ;
Access its member
apple.weight = 5;
apple.price = 9.9;
banana.weight = 10;
cout << apple.weight + banana.weight <<"\n"
Initialize
struct Movie {
string title;
int year;
};
Movie m1 = {"Inception", 2010};
Movie m2{"Interstellar", 2014};
function
struct Point{
int x, y;
};
Point add(Point a, Point b)
{
a.x += b.x;
a.y += b.y;
return a;
}
signed main() {
Point a = {1, 2};
Point b = {3, 4};
Point c = add(a, b);
cout << c.x << " " << c.y <<"\n";
return 0;
}Pointer
struct Point{
int x, y;
}*a;
Point b;
a = &b;
如何從a拿到b.x?
(*a).x
Pointer
struct Point{
int x, y;
}*a;
Point b;
a = &b;
如何從a拿到b.x?
a -> x
Sort
自訂comparator
int cmp(int &x, int &y)
{
return x > y;
}
signed main() {
int arr[] = {1, 2, 6, 5, 3};
sort(arr, arr + 5, cmp);
for(int i = 0; i < 5; i++)
cout << arr[i] << "\n";
return 0;
}使用call by ref: 避免不必要的複製
當 struct 裡有大物件(像 string 或大陣列)時,複製代價更高
Sort
struct Point {
int x, y;
};
bool cmp(const Point &a, const Point &b) {
if (a.x != b.x) return a.x < b.x;
return a.y < b.y;
}
int main() {
Point arr[] = {{3, 4}, {1, 2}, {3, 1}, {2, 5}};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n, cmp);
for (int i = 0; i < n; i++) {
cout << arr[i].x << " " << arr[i].y << "\n";
}
}
練習:
- a915. 二维点排序
C++ Struct
By ernestii26
C++ Struct
- 14