Accelerated C++, exercise 14.5 involves reimplementing a split
function (which turns text input into a vector of strings). One must use store input in a std::string
- like class (Str
) & use the split
function to return a Vec<Str>
, Vec
being a std::vector
- like container. The Str
class manages a custom pointer (Ptr
) to the underlying Vec<char> data
.
The Str
class provides a constructor Str(i,j)
, in Str.h
below, which constructs a Ptr
to the underlying Vec
The problem arises when I try to create substrings by calling str(i,j)
I've detailed in the code where the the issues arise.
Here is a whittled-down version of the Str
class (can post more code if needed):
Str.h
#include "Ptr.h"
#include "Vec.h"
class Str {
friend std::istream& operator>>(std::istream&, Str&);
public:
// define iterators
typedef char* iterator;
typedef char* const_iterator;
iterator begin() { return data->begin(); }
const_iterator begin() const { return data->begin(); }
iterator end() { return data->end(); }
const_iterator end() const { return data->end(); }
//** This is where we define a constructor for `Ptr`s to substrings **
template<class In> Str(In i, In j): data(new Vec<char>) {
std::copy(i, j, std::back_inserter(*data));
}
private:
// store a Ptr to a Vec
Ptr< Vec<char> > data;
};
Split.h
Vec<Str> split(const Str& str) {
typedef Str::const_iterator iter;
Vec<Str> ret;
iter i = str.begin();
while (i != str.end()) {
// ignore leading blanks
i = find_if(i, str.end(), not_space);
// find end of next word
iter j = find_if(i, str.end(), space);
// copy the characters in `[i,' `j)'
if (i != str.end())
ret.push_back(**substring**); // Need to create substrings here
// call to str(i,j) gives error, detailed below
i = j;
}
return ret;
}
My first thought was to use this constructor to create (pointers to) the required substrings. Calling str(i,j)
here gives the error message
type 'const Str' does not provide a call operator
- It appears as if one cannot simply call
str(i,j)
here. Why not? - Could a solution be to write a
Str
member function which is similar tosubstr
?