加速C ++,练习14.5涉及重新实现split
函数(将文本输入转换为字符串向量)。必须在std::string
类似的班级(Str
)中使用商店输入。使用split
函数返回Vec<Str>
,Vec
作为std::vector
类容器。 Str
类管理基础Ptr
的自定义指针(Vec<char> data
)。
Str
类在下面的Str(i,j)
中提供构造函数Str.h
,构造Ptr
到基础Vec
当我尝试通过调用str(i,j)
创建子字符串时出现问题
我已经详细介绍了问题出现的代码。
以下是Str
类的缩小版本(如果需要,可以发布更多代码):
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;
}
我的第一个想法是使用这个构造函数来创建(指向)所需的子串。在此处调用str(i,j)
会显示错误消息
type 'const Str' does not provide a call operator
str(i,j)
。为什么不呢?Str
类似的substr
成员函数?