编写一个类似PrintString的类,令其从istream中读取一行输入,然后返回一个表示我们所读内容的string。如果读取失败,返回空string
class PrintString{
public:
PrintString(std::istream &i = std::cin) :is(i){}
std::string operator()()const;
private:
std::istream &is; //std::istream is错误,不能将引用赋值给一个对象,因为引用不是对象,只是别名,可以将引用赋值给引用,将对象赋值给引用;
//std::string s;
};
inline std::string PrintString::operator()()const
{
std::string s;
std::getline(is, s); //为什么这样写报错呢?因为传过来的this指针为常量指针,故this->is和this->s都为常量,getline(is,s)函数无法修改is和s,getline只接受非常量对象
if (is.good())
return s;
else
return std::string();
}
使用标准库函数对象及适配器定义一条表达式,令其找到第一个等于pooh的字符串
适配器:函数适配器bind()函数,见C++primer P354
vector<string>svec;
string s;
while (cin >> s)
{
svec.push_back(s);
}
auto pos = find_if(svec.begin(), svec.end(), bind(equal_to<string>(), _1, "pooh")); //find_if 接受单一参数的调用对象,而要将“pooh”传进去,使用函数适配器进行
if (pos != svec.end())
cout <<"#"<< *pos << endl;
本文介绍了一个用于从输入流中读取字符串的C++类PrintString,并展示了如何使用标准库函数对象及适配器来查找包含特定字符串的元素。
438

被折叠的 条评论
为什么被折叠?



