数据结构与算法(青岛大学)

  1. C++中的变量引用
#include<iostream>
int a = 5;
int &r = a;

C++中的变量引用(reference)定义&,不是取地址运算符!!!初始化为变量a,不可修改。

  1. python中的变量
a = 4
print(a)
a = 'hello world!'
print(a)

由此推断出python中的变量是“引用型”,python中的值都是对象

#include <iostream>
#include <vector>
using namespace std;
class Table{
public:	
	int a;
	int b;
};
class DoubleTable{
public:	
	double a;
	double b;
};
int main(int argc, const char *argv[]){


	return 0;
}

为了解决代码复用的繁琐,C++中使用模板。

#include <iostream>
#include <vector>
using namespace std;
template<class T>
class Table{
public:	
	T a;
	T b;
};
int main(int argc, const char *argv[]){
	Table<int> t;
	t.a = 3;
	t.b = 4;
	Table<double> tt;
	tt.a = 3.5;
	tt.b = 4.5;

	return 0;
}

定义模板后,在创建对象时使用<type>指定类型即可。

C++中的vector向量其实是个模板。

#include <iostream>
#include <vector>
using namespace std;
template<class T>
class Table{
public:	
	T a;
	T b;
};
int main(int argc, const char *argv[]){
	vector<int> v;
	v.push_back(123);
	v.push_back(456);
	for(auto x : v)
		cout << x << endl;
	return 0;
}
123
456

重载友元操作符<<
为什么要这么干?
因为新写的类没有cout这个操作。

#include <iostream>
#include <vector>
using namespace std;
class Stu{
public:
	string id;
	int score;
	friend ostream& operator << (ostream& o, const Stu& s);
};
ostream& operator <<(ostream& o, const Stu& s){
	o << "(" << s.id << "," << s.score << ")";
	return o;
}
int main(int argc, const char* argv[]){
	Stu zs;
	zs.id = "S001";
	cout << zs << endl;

	return 0;
}

增加构造方法Stu(),更像一个类。

class Stu{
private:
	string id;
	int score;
public:
	Stu(string id, int score){
	this->id = id;
	this->score = score;
	}
	friend ostream& operator << (ostream& o, const Stu& s);
};
ostream& operator <<(ostream& o, const Stu& s){
	o << "(" << s.id << "," << s.score << ")";
	return o;
}
int main(int argc, const char* argv[]){
	Stu zs("S001",95);
	cout << zs << endl;

	return 0;
}

进一步把学生压到栈里面。

vector<Stu> v;
Stu zs("S001",95);
v.push_back(zs)

先构造zs,再拷贝到向量v里面去,多了一次拷贝。
可以这么干⬇️

vector<Stu> v;
v.emplace_back("S001",95);
v.emplace_back("S002",92);
cout << v << endl;

不可以输出!因为v也没有定义重载!!!

vector<Stu> v;
v.emplace_back("S001",95);
v.emplace_back("S002",92);
for(auto x:v)
	cout << x << endl;

这样就可以了。

(S001,95)
(S002,92)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值