【发布时间】:2019-02-04 03:11:01
【问题描述】:
我的代码中有以下for 语句:
for (auto Iter = Target.begin(),
IterEnd = std::stable_partition(Target.begin(), Target.end(), Check);
Iter != IterEnd; ++Iter)
{ /* loop statement */ }
关键是循环不会修改容器的元素,因此将迭代器声明为const_iterator 是有意义的。我可以使用cbegin() 轻松解决第一个问题,但第二个更复杂。我不能在stable_partition 中声明cbegin() 和cend(),因为当然stable_partition 需要non const_iterators 来完成它的工作。
一种可能的解决方案是将 auto 替换为正确的类型,在本例中为 std::vector< std::string >::const_iterator。这会强制在第二个分配中从 iterator 转换为 const_iterator。
虽然,我不喜欢它。类型可以轻松快速地变得难以管理,因此我正在寻找一种让我使用 auto 的解决方案,而无需在循环之外声明一些奇怪的东西。有什么建议吗?
【问题讨论】:
-
我不确定您对类型不可管理性的看法。如果这可以解决您的问题,那么在您的类型声明中明确是一种很好的方法。
auto很方便,但我不会说它一定比清楚您使用的类型更易于管理。 -
我肯定会把所有这些东西移出循环序幕。
auto Iter{Target.cbegin()}; decltype(Target)::const_iterator const IterEnd{std::stable_partition(Target.begin(), Target.end(), Check)}; -
你可以使用
decltype(Target.cbegin()) IterEnd -
小心你的术语:让迭代器 const doesn't 有意义,因为你会增加它。 ;)
-
还要注意
stable_partition重新排序Target的元素(也可能是第一个),所以Iter可能不指向第一个元素(取决于使用的容器)。在初始化Iter之前先调用stable_partition。
标签: c++ type-conversion const-iterator