美文网首页
Chapter 3. string, vector, array

Chapter 3. string, vector, array

作者: 永不摸鱼的小林 | 来源:发表于2020-04-28 17:37 被阅读0次

3.1. Namespace using Declarations

  • using declarations instead of using namespace is safer
using std::cin
  • don't use using declarations in header

3.2.string

  • string s(10, 'c') -> 'ccccccccc'

  • decltype(s.size()) punct_cnt = 0;
    不用引用库

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)
  • cctype library
    用于char
    isalpha
    islower
    ispunct
    isprint (is printable?)
    tolower
    toupper
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

  • vector<int> v1 {10}; // 1个为10元素的向量
  • vector<int> v2(10); //10个为0元素的向量
  • vector<int> v3 {10, 1}; //元素 1个为10, 1个为1的向量
  • vector<int> v4(10, 1); //10个为1元素的向量

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

  • vector<string> v1 {"hi"}; // 列表初始化,v1只有一个元素
  • vector<string> v2 ("hi"); // error
  • vector<string> v2 {10}; //10个default init元素的向量
  • vector<string> v2 {10, "hi"}; //10个为hi的向量
  • vector<int>::size_type size = vec.size();
    要加模板

  • v1 == v2 // v1 和 v2相等, 如果里面的元素个数相等且每个元素相等

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

  • char carray [] = "C++";
    no copy or assignment
    比如不能 char a2[] = carray, or a2 = carray
    strcpy

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;

相关文章

网友评论

      本文标题:Chapter 3. string, vector, array

      本文链接:https://www.haomeiwen.com/subject/oncbwhtx.html