本书为Primer C++ 中文第五版
学习笔记
命名空间的using声明
//using声明的形式如下
using namespace::name;
//eg.
int value;
std::cin >> value; <==> using std::cin; cin>>value;
std::cout<<value; <==> using std::cout;cout<<value;
头文件中不宜包含using声明,以防发生名字冲突;
标准库类型string
string表示可变长的字符序列,使用string类型必须首先包含string头文件,string定义在命名空间std中。 初始化string对象的方式
//eg.
string s1; //默认初始化,s1为空串
string s2(s1); //给s2赋s1的值
string s2 = s1; //等价于s2(s1)
string s3("value"); //给s3赋值value,直接初始化
string s3 = "value"; //等价于s3("value"),拷贝初始化
string s4(n,'c'); //给s4赋值为n个字符c组成的串,直接初始化
例子:
#include <iostream>
#include <string>
int main(){
//如果没有加std::,只使用string会报错
std::string s1 = "hello";
std::cout<<s1<<'\n';
return 0;
}
size函数返回的是一个string::size_type类型的值,所以尽量使用
auto len = line.size();
而不是使用int len = line.size();
当把string对象和字符字面值及字符串字面值混在一条语句中使用时,必须确保每个加法运算符(+)的两侧的运算对象至少有一个是string。
//eg.
string s1 = "hello";
string s2 = s1 + "world!"; //正确
string s3 = "hello" + "world!"; //错误
string s4 = s1 + ", " + "world!" ; //正确,相当于(s1+",")+"world!"
string s5 = "world" + " , " + s1; //错误
处理string中的每一个字符
/*
for (declaration: expression){
statement
}
declaration 定义一个变量,是序列中的基础元素
expression 是一个对象,表示一个序列
statement 对变量的操作
*/
//eg.
string str("some string");
for (auto : str){
cout<< c <<endl;
}
例子
#include <iostream>
#include <string>
#include <cctype>
void numpunct(std::string str) {
decltype(str.size()) punct_num = 0;
for(auto c : str) {
if(ispunct(c)) punct_num++;
}
std::cout<<str<<" has puncts : "<<punct_num<<"\n";
}
void toUp(std::string str) {
for(auto &c : str) {
c = toupper(c);
}
std::cout<<str<<"\n";
}
int main() {
std::string s1("hello,world!");
numpunct(s1);
toUp(s1);
return 0;
}
/*
输出结果为
hello,world! has puncts : 2
HELLO,WORLD!
*/
标准库类型vector
迭代器介绍
数组
eg.
#include <iostream>
#include <string>
#include <vector>
void test() {
int ia[] = {0,1,2,3,4};
//ia2 是指针
//auto 定义的变量必须有初始值
auto ia2(ia);
//ia3是数组
//ia3 = ia; 数组不允许拷贝
decltype(ia) ia3 = {0,1,2,3,4};
std::cout<<*ia2<<" "<<ia3[0]<<"\n";
}
void dou() {
std::vector<int> n;
for(int i=0; i<10; i++) {
n.push_back(i);
}
for(auto r : n) {
std::cout<<r<<" ";
}
std::cout<<"\n";
for(auto &r : n) {
r = 2*r;
}
for(auto r : n) {
std::cout<<r<<" ";
}
std::cout<<"\n";
}
int main(){
std::string s1 = "Hello";
std::string s2 = "Hiya";
std::cout<<(s2>s1)<<"\n";
std::cout<<('A'>'B')<<"\n";
std::string s = "some string";
if(s.begin() != s.end()) {
auto it = s.begin();
*it = toupper(*it);
}
std::cout<<s<<"\n";
for(auto it = s.begin(); it != s.end() && !isspace(*it); ++it) {
*it = toupper(*it);
}
std::cout<<s<<"\n";
dou();
test();
return 0;
}
/*
输出结果:
1
0
Some string
SOME string
0 1 2 3 4 5 6 7 8 9
0 2 4 6 8 10 12 14 16 18
0 0
*/