c++ - 将返回的迭代器转换为 const

标签 c++ type-conversion const-iterator

我有以下 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_partitionfor 之前.这将产生等效算法。

问题是 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/

相关文章:

ios - AnyObject 到阵列?

java - 如何从 int 转换为 String?

c++ - 为什么我的模板化函数需要从一个迭代器到另一个迭代器的转换?

c++ - QMultiMap以结构为键,结构为值,比较运算符

c++ - 通过强度值归一化图像的颜色 channel ,OpenCV

c++ - Qt - 如何将 QString 转换为 char(不是 char*)

c++ - 在 C++17 中,为什么关联容器有一个 `erase` 成员函数(非 -`const` ) `iterator` ?

c++ - `const_iterator` 真的需要与 `iterator` 属于不同的类吗?

c++ - gcc-4.9 无法编译#include "user defined file"

c++ - DSSCL_EXCLUSIVE 不提供独占的音频输出。 DirectSound