Code:
namespace MyNamespace {
// Stuff goes here. Functions, declarations, types, classes, etc...
}
As a quick example, the following code defines a simple treap type within the Ed namespace. Appologies if there are any errors, I wrote it in haste.
Code:
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
namespace Ed {
class Treap {
private:
struct node {
int content;
int priority;
node *left;
node *right;
node(int init)
: content(init)
, priority(std::rand())
{ left = right = 0; }
};
public:
Treap()
: root(0)
, sz(0)
{};
~Treap() { destroy(root); }
void insert(int item) { root = r_insert(root, item); }
void remove(int item) { root = r_remove(root, item); }
node *search(int item) { return r_search(root, item); }
void structure() { r_structure(root, 0); }
private:
node *r_insert(node* curr, int item);
node *r_remove(node *curr, int item);
node *r_search(node *curr, int item);
void r_structure(node *curr, int height);
void destroy(node *curr);
private:
node *root;
int sz;
};
Treap::node *Treap::r_insert(node* curr, int item)
{
if (curr == 0)
curr = new node(item);
else if (item < curr->content) {
curr->left = r_insert(curr->left, item);
if (curr->priority < curr->left->priority) {
node *temp = curr->left;
curr->left = temp->right;
temp->right = curr;
curr = temp;
}
}
else if (item > curr->content) {
curr->right = r_insert(curr->right, item);
if (curr->priority < curr->right->priority) {
node *temp = curr->right;
curr->right = temp->left;
temp->left = curr;
curr = temp;
}
}
return curr;
}
Treap::node *Treap::r_remove(node *curr, int item)
{
return root;
}
Treap::node *Treap::r_search(node *curr, int item)
{
if (curr == 0)
return 0;
else if (item < curr->content)
return r_search(curr->left, item);
else if (item > curr->content)
return r_search(curr->right, item);
else
return curr;
}
void Treap::r_structure(node *curr, int height)
{
if (curr == 0) {
for (int n = 0; n < height; n++)
cout<<'\t';
cout<<'*'<<endl;
}
else {
r_structure(curr->right, height + 1);
for (int n = 0; n < height; n++)
cout<<'\t';
cout<< curr->content <<endl;
r_structure(curr->left, height + 1);
}
}
void Treap::destroy(node *curr)
{
if (curr == 0)
return;
destroy(curr->left);
destroy(curr->right);
delete curr;
}
}
int main()
{
Ed::Treap t;
int c;
while (std::cin>> c) {
t.insert(c);
t.structure();
cout<<"\n==============\n";
}
}
One nice feature of namespaces is that if I wanted to later add another type to the Ed namespace, I would not have to edit this code.
Code:
namespace Ed {
// Stuff
}
namespace Ed {
// More stuff
}
Both Stuff and More stuff are a part of the Ed namespace even though there are two declarations of said namespace.