Chapter 3. string, vector, array

2020-04-28  本文已影响0人  永不摸鱼的小林

3.1. Namespace using Declarations

using std::cin

3.2.string

const int&& foo();
int i;
struct A { double x; };
const A* a = new A();

decltype(foo())  x1;  // const int&&      (1)
decltype(i)      x2;  // int              (2)
decltype(a->x)   x3;  // double           (3)
decltype((a->x)) x4;  // double&          (4)
string s ("hello");
for (auto &c : s)
  c = toupper(c);

string::size_type size = str.size();
// typedef typename allocator_traits<allocator_type>::size_type
和分配器有关

在 C++ 中,traits 习惯上总是被实现为 struct ,但它们往往被称为 traits classes。Traits classes 的作用主要是用来为使用者提供类型信息。

3.3.vector

curly braces{} 会优先使用list constructor 如果不行, 就会找其他方法

3.3.1 iterator

*iter // 返回的是其对应数据的引用形式,改变直接改变值
iter->member
++iter
iter == iter2
ptr也可以这样操作

sting s {"adasdas asdad a sad"};
for (auto it = s.begin(); it != s.end() && !isspace(*it); ++it)
{
  *it = toupper(*it);
}

vector<int>::iterator

不能在range-based 循环里增加vector的元素,因为可能导致vector的扩容dynamically allocate,导致问题(此时end会变 ++this->__end)

iterator可做数字运算
iter-=4
iter < iter2 对比出现位置是否比iter2早

3.5.Array

null terminate for char array
’\0'
string库里用于char数组的函数
strlen
strcat
strcpy
strcmp

strcmp和两个字符串对比一样,比对指针的值而不是string。

int a[3][2] = {1,2,3,4,5,6};
int a[3][2] = {{1,2}, {3,4}, {5,6}};

ranged-loop

int a[3][2] = {{1,2}, {3,4}, {5,6}};
size_t cnt = 0;
for (auto &row: a)
  for (auto &col : row)
    cout << col << endl;
上一篇 下一篇

猜你喜欢

热点阅读