Bloomberg LP Interview Question
Software Engineer / DevelopersTeam: Price history
Country: United States
Interview Type: In-Person
#include <iostream>
#include <map>
using namespace std;
class mmap : public map<string, map<string, string> >
{
public:
map<string, string>& operator [] (const string& arg)
{
if (this->find(arg) == this->end()) {
map::operator[] (arg) = map<string, string>();
}
return map::operator[](arg);
}
};
int main()
{
mmap obj = mmap();
obj["string1"] ["string2"] = "Some value!";
cout << &obj["string1"] << endl;
cout << obj["string1"]["string2"] << endl;
}
I didn't get why derived class need to define operator[] ? I'd understood if you use `private' inheritance and then just:
public:
using Base:operator[];
And typedef can do that too:
typedef std::map<std::string, std::map<std::string, std::string> mmap;
And use a template to make it contain generic types.
template <typename T>
class mmap: private std::map<std::string, std::map<std::string, std::string>>
{
public:
using std::map<std::string, std::map<std::string, std::string>>::operator[];
};
Sorry, I meant:
template <typename T>
class map3 :private std::map<std::string, std::map<std::string, T>>
{
public:
using std::map<std::string, std::map<std::string, T>>::operator[];
};
A working code for this
#include <iostream>
#include <string>
#include <map>
#include <unordered_map>
using namespace std;
template <typename T>
class classMap
{
private:
map<string, map<string, T> > mmap;
public:
classMap()
{
}
~classMap(){};
map<string, string>& operator [](string str)
{
if(mmap.find(str) == mmap.end())
mmap[str] = map<string, T>();
return mmap[str];
}
void getData()
{
for(typename map<string, map<string, T> >::iterator it = mmap.begin(); it != mmap.end(); ++it)
{
cout<<it->first<<" , ";
typename map<string, T>::iterator it_second = (it->second).begin();
cout<<it_second->first<<" , "<<it_second->second<<endl;
}
}
};
int main(int argc, char const *argv[])
{
classMap<string> c;
c["rob"]["van"] = "dam";
c["the"]["big"] = "show";
c.getData();
return 0;
}
just making compiler compliant. no meaning.
- suresh August 22, 2014#include <iostream>
using namespace std;
class test
{
int male;
int female;
string why;
public:
test& operator[](string a)
{
if (a == "male")
++male;
else
++female;
return *this;
}
test& operator=(string a)
{
why=a;
return *this;
}
};
int main()
{
test a;
a["male"]["female"] = "super";
return 0;
}