https://rentry.org/PPP2_p272

// Code derived from Stroustrup's PPP2 book
// § 8.5.1 Declaring arguments and return type
//  -and beginning on p 272

#include <iostream>
#include <string>
#include <vector>

using namespace std;

double fct(int a, double d);  // declaration of fct (no body)

double fct(int a, double d)  // definition of fct
{
  return a * d;
}

//---

int current_power();  // current_power doesn't take an argument

void increase_power(int level);  // increase_power doesn't return a value

//---

// search for s in vs;
// vs[hint] might be a good place to start the search
// return the index of a match; -1 indicates "not found":
int my_find(vector<string> vs, string s, int hint);  // naming arguments

int my_find(vector<string>, string, int);  // not naming arguments

// search for s in vs starting at hint
int my_find(vector<string> vs, string s, int hint)
{
  if (hint < 0 || (int)vs.size() <= hint)
    hint = 0;

  for (int i = hint; i < (int)vs.size(); ++i)  // search starting from hint
    if (vs[i] == s)
      return i;

  if (0 < hint) {  // if we didn't find s search after hint

    for (int i = 0; i < hint; ++i)
      if (vs[i] == s)
        return i;
  }

  return -1;  // means failure (didn't find)
}

namespace different {

int my_find(vector<string> vs, string s, int)  // 3rd argument unamed, unused
{
  for (int i = 0; i < (int)vs.size(); ++i)
    if (vs[i] == s)
      return i;

  return -1;  // means failure (didn't find)
}

}  // namespace different

//---

// bonus:
int main()
{
  const int   N         = 4;
  const char* cities[N] = {"Aarhus", "Brussels", "Cincinnati", "Dublin"};
  //
  vector<string> v(cities, cities + N);  // constructed from C-array of C-string

  // do the two versions of my_find() produce the same results? :

  bool same = (my_find(v, "Dublin", 2) == different::my_find(v, "Dublin", 2));
  cout << std::boolalpha;
  cout << same << '\n';
}

build & run:

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

PrevUpNext

Edit
Pub: 04 Apr 2023 14:36 UTC
Edit: 02 May 2023 23:32 UTC
Views: 353