我有以下 for
我的代码中的语句:
for (auto Iter = Target.begin(),
IterEnd = std::stable_partition(Target.begin(), Target.end(), Check);
Iter != IterEnd; ++Iter)
{ /* loop statement */ }
重点是循环不会修改容器的元素,因此将迭代器声明为 const_iterator
是有意义的.我可以轻松解决第一次使用 cbegin()
的问题,但第二个更复杂。我不能申报 cbegin()
和 cend()
里面stable_partition
,因为当然stable_partition
需求non const_iterators
完成它的工作。
一个可能的解决方案是将 auto 替换为正确的类型,在本例中为 std::vector< std::string >::const_iterator
.这会强制从 iterator
进行转换至 const_iterator
关于第二个作业。
不过,我不喜欢。类型可以轻松快速地变得难以管理,因此我正在寻找一种解决方案,让我可以使用 auto,而无需在循环外声明一些奇怪的东西。有什么建议吗?
最佳答案
我认为最明确的解决方案是拉取 std::stable_partition
在 for
之前.这将产生等效算法。
问题是 stable_partition
返回一个可以修改元素的迭代器。幸运的是,有一个从 container::iterator
的隐式转换至 container::const_iterator
(对于大多数标准容器)。要进行转换,您可以指定 IterEnd
的类型与 std::vector<T::const_iterator
, 或 decltyp(Target.cbegin()
或者我个人的喜好:
auto Iter = Target.cbegin();
decltype(Iter) IterEnd = std::stable_partition(Target.begin(), Target.end(), Check);
for (; Iter != IterEnd; ++Iter)
{
}
为了完整起见,您可以将所有内容保留在 for
中如果您愿意,但我认为它的可读性较差:
for (auto Iter = Target.cbegin(),
IterEnd = (decltype(Iter)) std::stable_partition(Target.begin(), Target.end(), Check);
Iter != IterEnd;
++Iter)
{}
关于c++ - 将返回的迭代器转换为 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52075579/