Bloomberg LP Interview Question
Software Engineer / DevelopersI think its easy to write a template to add int, float...
template<class T>
T addarray(T *v, int n)
{
T sum=0;
for(i=0;i<n;i++)
{
sum+=v[i];
}
return sum;
}
but for char and string the above code template shld be changed...I donno how we can write a generic code for all the four different data types for both add & concatenate...
Since we do not know what type of data is present inside the array(int,float,char), the trick is to identify the data type first. To do that, we can increment pointer location.
Example
if ptr points to first block of the array, then (ptr+1) points to second position in the array. Find the difference between both the blocks of memory.
If they are separated by 8 bytes, its char
separated by 32 bytes its int
separated by 64 bytes, its float.
At first, the result can be define as a class with member functions of + and += operators
I guess we can define the opertator + and += as pure vitual function in the base class. Then define derived classes to accept int/float/char/string. In these derived classes, redine the + and +=. Use the reference of the base class to call + and += dynamcially.
class sum{
public:
virtual sum& operator+=(const sum&) = 0;
}
class sum_int: public sum{
public:
sum_int(const int&);
sum_int& operator+=(const sum_int&);
}
class sum_float: public sum{
public:
sum_float(const float&);
sum_float& operator+=(const sum_float&);
}
class sum_string: public sum{
public:
sum_string(const string&);
sum_string& operator+=(const sum_string&);
}
With some template tricks, we can deduce the correct return type using another simple template, so the main template doesn't need any specialization:
template<typename T>
struct Aggregate {
typedef T type;
};
template<>
struct Aggregate<char> {
typedef string type;
};
template<typename T>
typename Aggregate<T>::type combine(T *first, size_t N) {
typename Aggregate<T>::type sum = typename Aggregate<T>::type();
for (T *p = first; p < first + N; ++p) {
sum += *p;
}
return sum;
}
I think you can start with visiting each element from ptr to ptr + sizeof(ptr)/sizeof(ptr[0])..if the ptr was defined as an array.
- Anonymous December 07, 2009Now you have the pointer to each element...
Was this to be done in C or C++?