【发布时间】:2012-12-12 20:53:32
【问题描述】:
我目前已启动并运行此代码:
string word="test,";
string::iterator it = word.begin();
for (; it != word.end(); it++)
{
if (!isalpha(*it)) {
break;
}
else {
*it = toupper(*it);
}
}
word.erase(it, word.end());
// word should now be: TEST
我想让它更紧凑和可读:
- 组合现有的标准 C++ 算法 (*)
- 只执行一次循环
(*) 我假设结合现有算法会使我的代码更具可读性...
另一种解决方案
除了按照 jrok 的建议定义自定义 transform_until 算法之外,还可以定义自定义迭代器适配器,该适配器将使用底层迭代器进行迭代,但通过在返回之前修改底层引用来重新定义 operator*() .
类似的东西:
template <typename Iterator, typename UnaryFunction = typename Iterator::value_type (*)(typename Iterator::value_type)>
class sidefx_iterator: public std::iterator<
typename std::forward_iterator_tag,
typename std::iterator_traits<Iterator>::value_type,
typename std::iterator_traits<Iterator>::difference_type,
typename std::iterator_traits<Iterator>::pointer,
typename std::iterator_traits<Iterator>::reference >
{
public:
explicit sidefx_iterator(Iterator x, UnaryFunction fx) : current_(x), fx_(fx) {}
typename Iterator::reference operator*() const { *current_ = fx_(*current_); return *current_; }
typename Iterator::pointer operator->() const { return current_.operator->(); }
Iterator& operator++() { return ++current_; }
Iterator& operator++(int) { return current_++; }
bool operator==(const sidefx_iterator<Iterator>& other) const { return current_ == other.current_; }
bool operator==(const Iterator& other) const { return current_ == other; }
bool operator!=(const sidefx_iterator<Iterator>& other) const { return current_ != other.current_; }
bool operator!=(const Iterator& other) const { return current_ != other; }
operator Iterator() const { return current_; }
private:
Iterator current_;
UnaryFunction fx_;
};
当然,这仍然很原始,但它应该给出想法。 使用上述适配器,我可以编写以下内容:
word.erase(std::find_if(it, it_end, std::not1(std::ref(::isalpha))), word.end());
预先定义以下内容(可以通过一些模板魔术来简化):
using TransformIterator = sidefx_iterator<typename std::string::iterator>;
TransformIterator it(word.begin(), reinterpret_cast<typename std::string::value_type(*)(typename std::string::value_type)>(static_cast<int(*)(int)>(std::toupper)));
TransformIterator it_end(word.end(), nullptr);
如果标准包含这样的适配器,我会使用它,因为这意味着它完美无缺,但由于情况并非如此,我可能会保持我的循环不变。
这样的适配器将允许重用现有算法并以不同方式混合它们,这在今天是不可能的,但它也可能有缺点,我现在可能会忽略...
【问题讨论】:
-
在我当前的代码中有一个循环。我的观点是,重写后仍然会有一个循环。
-
基于
!isalpha(*it)的过早出走是我认为唯一可能阻止你实现我认为你正在寻找的东西,老实说,任何可能为你做的事情(我可以'不会立即看到任何东西)可能会如此令人费解,你的清晰度因素会消失在窗外。我可能会坚持你所拥有的。 -
感谢大家鼓舞人心的回答。我现在将坚持我当前的代码。我相信
boost::transform_iterator是我正在寻找的最接近的东西。这个用例将被一个“副作用”迭代器适配器覆盖,使用如下:word.erase(std::find_if(sidefx_iterator(word.begin(), ::toupper), word.end(), std::not1(::isalpha)), word.end());
标签: c++ algorithm stl c++11 std