C++学习笔记(一)


由于专业课选课失败,老师上课不咋讲课,按着书和慕课自学……

string

和C的区别

C++的字符串在C的基础上进行了扩充,在引入了保留字“string”的基础上,承认字符串间赋值、运算合法。

char charr1[20];
char charr2[20] = "string_C";
string str1;
string str2 = "string_Cpp";
charr1 = charr2;	// Invalid
str1 = str2;		// Valid
string str3;
str3 = str1 + str2;	// Valid
str3 += "ZJU"		// Valid

字符串的输入

正常的cin与C语言一样接受输入直到空格为止。
面向行的输入

cin.getline(name, n);	// 读取(n-1)个字符至name字符串中
cin.get(name, n);		// 会将换行符读入到字符串中并保留
cin.get(name, n).get()	// 读入两次字符串(有换行符)。

之所以可以这样做,是因为cin.get()函数会返回一个cin的对象。

Reference

type& rename = name;

变量rename即为name,引用在绝大多数情况下需要赋初始值,但在传入函数参数时可以默认为自动赋初始值,引用可以实现在函数内部更改参数的值。

void f(int &a){
    cout << "in f() " << a << endl;
    a = 30;
    cout << "in f() " << a << endl;
}
int main() {
    int i = 10;
    cout << "in main " << i << endl;
    f(i);
    cout << "in main " << i << endl;
    return 0;
}

//  输出为
// in main 10
// in f() 10
// in f() 30
// in main 30

而如果修改main函数为

int main(){
	int i = 10;
	f(3 * i);
	return 0;
}

程序会报错,这是由于f函数需要的是一个引用的变量,而非值。

:: resolver

void S::f(){	// f is a member function of calss S.
	::f();		// Visit a global function.
	::a++;		// a is a global variable.
	a--;		// a is a member variable of class S.
}

Definition of a class

  1. In C++, separated .h and .cpp files are used to define one class.
  2. Class declaration and prototypes in that class are in the header file (.h).
  3. All the bodies of these functions are in the source file (.cpp).

STL (Standard Template Library)

Containers

  1. Vector (expandable array)
  2. Deque (expandable array, expand at both ends)
  3. List (double-linked)
  4. Sets and Maps

Vector

#include <iostream>
#include <vector>
using namespace std;
int main(){
	vector<int> x;
	for (int i = 0; i < 100; i++){
		x.push_back(a);
	}
	vector<int>::iterator p;
	for (p = x.begin(); p < x.end(); p++){
		cout << *p << endl;
	}
	return 0;
}
Basic Vector Operation
// Constructors
vector<Elem> c;
vector<Elem> c1(c2);	// 基于c2构建c1
// Simple Method
V.size();
V.empty();
==, !=, <, >, <=, >=;
V1.swap(V2);
// Iterators
I.begin();
I.end();
// Element Access
V.at(index); == V[index];
V.front();
V.back();
// Others
V.push_back(e);
V.pop_back();
V.insert(pos, e);
V.erase(pos);
V.clear();
V.find(first, last, item);

List

As it is double linked, it has more operations than vector:

x.push_front(item);
x.pop_front(item);

Maps

Maps are collection that contain pairs of values.
Pairs consist of a key and a value.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值