The Technical Report on C++ Library Extensions

by Matthew H. Austern



Listing One



#include <tr1/unordered_map>

#include <iostream>

#include <string>



int main() 

{

  using namespace std;

  using namespace std::tr1;  

  typedef unordered_map<string, unsigned long> Map;

  Map colors;



  colors["black"] = 0xff0000ul;

  colors["red"] = 0xff0000ul;

  colors["green"] = 0x00ff00ul;

  colors["blue"] = 0x0000fful;

  colors["white"] = 0xfffffful;



  for (Map::iterator i = colors.begin(); 

       i != colors.end(); 

       ++i)

  cout << i->first << " -> " << i->second << endl;

}





Listing Two



#include <iostream>

#include <tr1/memory>



using namespace std;

using namespace std::tr1;



struct A {

  A() { cout << "Create" << endl; }

  A(const A&) { cout << "Copy" << endl; }

  ~A() { cout << "Destroy" << endl; }  

};



int main() {

  shared_ptr<A> p1(new A);

  shared_ptr<A> p2 = p1;

  assert (p1 != NULL && p2 != NULL && p1 == p2);

}



Listing Three



class my_node {

public:

  ...

private:

  weak_ptr<my_node> parent;

  shared_ptr<my_node> left_child;

  shared_ptr<my_node> right_child;

}; 



Listing Four



#include <tr1/functional>

#include <vector>

#include <iostream>



using namespace std;

using namespace std::tr1;



struct my_class

{

  void f() { cout << "my_class::f()" << endl; }

};



void g(my_class) {

  cout << "g(my_class)" << endl;

}



struct h {

  void operator()(my_class) const {

    cout << "h::operator()(my_class)" << endl;

  }

};



int main()

{

  typedef function<void(my_class)> F;

  vector<F> ops;

  ops.push_back(&my_class::f);

  ops.push_back(&g);

  ops.push_back(h());



  my_class tmp;

  for (vector<F>::iterator i = ops.begin();

       i != ops.end();

       ++i)

    (*i)(tmp);

}





Listing Five



#include <regex>

#include <string>

#include <iostream>



using namespace std;

using namespace std::tr1;



bool

do_grep(const string& exp, istream& in, ostream& out)

{

  regex r(exp);

  bool found_any = false;

  string line;



  while (getline(in, line))

    if (regex_search(line, r)) {

      found_any = true;

      out << line;

    }



  return found_any;

}



Listing Six



(a)

const string datestring = "10/31/2004";

const regex r("(\\d+)/(\\d+)/(\\d+)");

smatch fields;

if (!regex_match(datestring, fields, r))

  throw runtime_error("not a valid date");



const string month = fields[1];

const string day = fields[2];

const string year = fields[3];





(b)

const string date = "10/31/2004";

const regex r("(\\d+)/(\\d+)/(\\d+)");

const string date2 = regex_replace(date, r, "$2/$1/$3");











3



