Aug 2, 2011 at 4:08pm UTC
Hello
Im having a problem undrestanding a code providied by my school as a help for exam.
Here is the Code:
#include <algorithm>
#include <functional>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <map>
#include <string>
#include <utility>
using namespace std;
namespace std
{
ostream& operator<<(ostream& os, const pair<string, int>& p)
{
return os << setw(8) << left << p.first << p.second;
}
ostream& operator<<(ostream& os, const pair<int, string>& p)
{
return os << setw(8) << left << p.second << p.first;
}
}
int main()
{
map<string, int> dog_names;
string name;
while (cin >> name)
{
++dog_names[name];
}
copy(dog_names.begin(), dog_names.end(),
ostream_iterator< pair<string, int> >(cout, "\n"));
cout << endl;
multimap<int, string, std::greater<int> > dog_names_ranked;
for (map<string, int>::const_iterator it = dog_names.begin();
it != dog_names.end();
++it)
{
dog_names_ranked.insert(make_pair(it->second, it->first));
}
copy(dog_names_ranked.begin(), dog_names_ranked.end(),
ostream_iterator< pair<int, string> >(cout, "\n"));
return 0;
}
Now the part I dont undrestand is:
namespace std
{
ostream& operator<<(ostream& os, const pair<string, int>& p)
{
return os << setw(8) << left << p.first << p.second;
}
ostream& operator<<(ostream& os, const pair<int, string>& p)
{
return os << setw(8) << left << p.second << p.first;
}
}
why make a namespace with the name std? we are alredy using namespaces std;
and how are we manipulating the << ? When are we using this namespace anyway??
I would apricate a answer
Thx!!
Aug 2, 2011 at 4:19pm UTC
You are just extending the std namespaces functionality. for example before you could say
std::cout << "hello" ;
and
std::cout << 5+74;
after our code you can also say cout << somepair;
i think not completely sure :/
Last edited on Aug 2, 2011 at 4:22pm UTC
Aug 2, 2011 at 5:11pm UTC
Thank you,,
it now make sense.
but if I change the namespace name to ex "bart" and then call the namespace whenever i need to use it. eg .. bart::greater<int>. But it dosent compile... So we are only extending the std namespaces.
My question Now is: What dose this do ?
ostream& operator<<(ostream& os, const pair<string, int>& p)
{
return os << setw(8) << left << p.first << p.second;
}
and espacially : ostream& operator<<(ostream& os, const pair<string, int>& p)
Aug 2, 2011 at 5:29pm UTC
well you need to implement cout also in bart namespace. and thats friggin hard i think
Last edited on Aug 2, 2011 at 5:29pm UTC