zoukankan      html  css  js  c++  java
  • [c++] 引用

    1、使用引用避免拷贝

    c++中拷贝大的类类型对象或容器对象比较低效,甚至有的类型不支持拷贝,这种情况下只能通过引用形参访问该类型的对象

    当函数无需修改引用形参的值时,最好使用常量引用

    例1:返回两个字符串中较短的那个

     1 #include <iostream>
     2 #include <string>
     3 using namespace std;
     4 using std::string;
     5 
     6 const string &shorterString(const string &s1, const string &s2) {
     7     return s1.size() <= s2.size() ? s1 : s2;
     8 }
     9 int main() {
    10     string s1 = "hello";
    11     string s2 = "hi";
    12     string s = shorterString(s1,s2);
    13     cout << s << endl;
    14 }

    结果:hi

    最终s返回的是较短字符的引用

    2、函数返回多个值

     1 #include <iostream>
     2 #include <string>
     3 using namespace std;
     4 using std::string;
     5 
     6 string::size_type find_char(const string &s, char c,
     7     string::size_type &occurs) {
     8     auto ret = s.size();
     9     occurs = 0;
    10     for (decltype(ret) i = 0; i != s.size(); ++i) {
    11         if (s[i] == c) {
    12             if (ret == s.size())
    13                 ret = i;
    14             ++occurs;
    15         }
    16     }
    17     return ret;
    18 }
    19 
    20 int main() {
    21     string s = "helloo";
    22     string::size_type ctr;
    23     auto index = find_char(s, 'o', ctr);
    24     cout << ctr << endl;
    25 }

    输出:2

    参考:

    《c++ primer》(第五版)

  • 相关阅读:
    EF 使用 oracle
    mysql安装笔记
    解决问题
    第四次冲刺
    第三次冲刺
    SQA
    第二次冲刺
    第一次冲刺,求进步
    Scrum _GoodJob
    我对git 、github的初印象
  • 原文地址:https://www.cnblogs.com/cxc1357/p/10561533.html
Copyright © 2011-2022 走看看