0. CPPGuide

https://zh.cppreference.com/w/cpp/string/basic_string/substr

1. reference:专治变量,类等

int * const r;

  1. 必须赋初始值
  2. 不可改变引用的指向

  3. const int & r;(const int * const r)

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. int a = 5;
  6. int b = 10;
  7. // int &r1; //[Error] 'r' declared as reference but not initialized
  8. int &r2 = a;
  9. // &r2 = b; //[Error] lvalue required as left operand of assignment
  10. const int &r3 = a;
  11. // r3 = b; //[Error] assignment of read-only reference 'r3'
  12. return 0;
  13. }

2. new

3. function

4. 类型说明符

  1. auto
  2. decltype(var or exp)
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. //返回在string对象中某个指定字符第一次出现的位置,同时返回该字符出现的总次数
  5. inline string::size_type find_char(const string& s, char c, string::size_type& occurs)
  6. {
  7. auto ret = s.size();
  8. for(decltype(ret) i = 0; i< s.size(); i++)
  9. {
  10. if(s[i]==c)
  11. {
  12. if(ret == s.size())
  13. ret = i;
  14. occurs++;
  15. }
  16. }
  17. return ret;
  18. }
  19. int main()
  20. {
  21. string s = "hello world";
  22. string::size_type occurs = 0;
  23. cout << find_char(s, 'l', occurs) << endl;
  24. cout << occurs << endl;
  25. return 0;
  26. }
  • const string& s
  • 不能返回string::size_type&因为ret是函数内部创建的变量,执行完会被销毁,因此不能传ret的引用,即不能传临时变量的引用
  • 增加occurs从而使函数返回更多的信息(值)
  • 可设置inline





**