https://rentry.org/PPP2_p277

// Code derived from Stroustrup's PPP2 book
// § 8.5.4 Pass-by-const-reference
//  -and beginning on p 277

#include <iostream>
#include <vector>

using namespace std;

void print(const vector<double>& v)  // pass-by-const-reference
{
  cout << "{ ";

  for (int i = 0; i < (int)v.size(); ++i) {
    cout << v[i];

    if (i != (int)v.size() - 1)
      cout << ", ";

    //---

    // v[i] = 7;  // error: v is a const (is not mutable)
  }

  cout << " }\n";
}

void f(int x)
{
  vector<double> vd1(10);     // small vector
  vector<double> vd2(10000);  // large vector
  vector<double> vd3(x);      // vector of some unknown size

  // ... fill vd1, vd2, vd3 with values ...

  print(vd1);
  print(vd2);
  print(vd3);
}

//------------------------------------------------------------------------------

// call-by-value: copy
int my_find(vector<string> vs, string s);

// call-by-const-reference: no copy, read-only access (for both vs and s)
int my_find(const vector<string>& vs, const string& s);

//------------------------------------------------------------------------------

int main() { f(10); }

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_08/main_p277.cpp && ./a.out

PrevUpNext

Edit
Pub: 04 Apr 2023 14:47 UTC
Edit: 02 May 2023 23:38 UTC
Views: 558