【数据结构】(一)模板 重载

it2024-05-06  56

1 C++ 基本语法

1.1 模板函数

// T 可以改为其他名字,如 Item // template <typename T1, T2...> template <typename T> void swap(T &a, T &b) { T temp; temp = a; a = b; b = temp; }

1.2 函数重载

// 返回值 ,参数个数... int add(int &a, int &b) { return a + b; } // 参数量不同的重载 int add(int &a, int &b, int c) { return a + b + c; }

1.3 结构体

//声明 struct Student { string name; int age; }; //[1] use 普通 --------------------------------- Student s1 = {"xhh", 18}; cout << s1.name << " " << s1.age << endl; //[2] use 指针 --------------------------------- Student *s2 = new Student{"xhh2", 19}; //Student *s2 = new Student; //s2->name = "xhh2"; //s2->age = 19; cout << s2->name << " " << s2->age << endl; //[2] use 数组 --------------------------------- Student ss[2]; for(int i = 0; i < 2; i++) { cout << "name:"; cin >> ss[i].name; cout << "age:"; cin >> ss[i].age; }

1.4 类

//声明 class Person { private: string name; int age; public: Person() {};//默认构造 Person(string name, int age) { this->name = name; this->age = age; } ~Person(){};//析构函数 string getName() { return this->name; } int getAge(); }; Person::getAge() { return this->age; } //使用 //Person p1("zph", 19); Person p1 = Person("xhh", 18); cout << "name:" << p1.getName() << endl; cout << "age:" << p1.getAge() << endl; Person* p2 = new Person("zph", 19); cout << "name:" << p2->getName() << endl;

1.5 数组

char s[10]; string name = "xhh"; strcpy(s, name.c_str()); cout << s;

2 一些小技巧

2.1 typedef

//typedef 已有类型名(结构体) 新名 typedef int ElemType; ElemType num = 18; cout << num << endl;

3 Summary

线性表(顺序/链式)

树(顺序/链式)

图(符合存储)

时间复杂度

最新回复(0)