C++ Primer 第三章 字符串,向量和数组

时间:2020-06-03 22:39:47   收藏:0   阅读:66

第三章 字符串,向量和数组

3.1 using声明

3.2 string

3.2.1 定义和初始化

string s = string(10,‘c‘);
//等价于
string tmp(10,‘c‘);
string s = tmp;

3.2.2 对象上的操作

string s6 = s1 + ", " + "world";
//等价于
string s6 = (s1 + ", ") + "world"; //正确

string s7 = "hello" + ", " + s2;
//等价于
string s8 = ("hello" + ", ") + s2; //错误,两个字符串字面值不能加在一起

3.2.3 处理string对象中的字符

//例如把string中的每个字符每行一个输出
string str("some string");
for (auto c : str) {
    cout << c << endl; 
}
string str("some string");
for(char & c : str) {
    c = toupper(c);
}

3.3 标准库类型vector

3.3.1 定义和初始化

//默认初始化
vector<string> a;
//列表初始化
vector<string> v1 = {"a","an","the"};
//创建指定数量的初始化
vector<string> ivec(10,"hi"); //创建包含10个hi的vector
vector<int> ivec(10); //创建10个元素,每个都是0

3.3.2 向vector添加元素

3.4 迭代器

3.4.1 使用迭代器

3.4.2 迭代器运算

3.5数组

3.5.1 定义和初始化

int *ptrs[10]; //指向10个int指针的数组
int &refs[10] = ...;  //不存在引用的数组
int (*Parray)[10] = &arr; //指向大小为10的int数组
int (&arrRef)[10] = &arr; //表示一个大小为10的int数组的引用

3.5.2 访问数组元素

3.5.3 指针和数组

3.5.4 C风格字符串

3.6 多维数组

int ia[3][4]; //大小为3的数组,每个元素是含有4个int的数组
int arr[10][20][30]; //大小为10的数组,每个元素是大小为20的数组,这些数组的元素含是有30个int的数组
size_t cnt = 0;
for (auto &row : ia) { 
  for (auto &col : row) {
    col = cnt;
    cnt++;
  }
}
//因为我们需要修改数组的元素,所以我们很容易想到去使用引用
for (const auto &row : ia) { //auto->int[4]
  for (auto col : row) {   //auto->int
    cout << col << endl;
  }
}
//但是这个程序,我们依然使用了引用,原因是auto如果不引用,会把col当成是一个普通的指针而非数组
using int_array = int[4];
typedef int int_array[4];

原文:https://www.cnblogs.com/Hugh-Locke/p/13040330.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!