在 C++ 中,如何乘以包含 std::variant 元素的向量的迭代器?进行迭代器类型的转换?

In C++ how does one multiply an iterator of a vector which contains std::variant elements? Doing a cast of the iterator type?

#include <iostream>
#include <vector>
#include <string>
#include <variant>

struct S1 { int a {}; };
struct S2 { std::string b {}; };
using Struct_variant = std::variant< S1, S2 >;

int main() {
    std::vector<Struct_variant> struct_vector { S1 {1}, S2 {"hello"}, S1 {3}};
    size_t index_to_erase {1};  // NOTE: assume we only know the index, *not* the iterator.
    auto variant_itr = struct_vector.begin();

    // following line requires either a std::vist, or an "if std::holds_alternative" to handle types.
    variant_itr =  struct_vector.begin() * index_to_erase;
    // for (int i = 0; i != index_to_erase; i++) variant_itr++;  // works
    struct_vector.erase(variant_itr);
    std::cout << struct_vector.size() << std::endl;
}

我不完全理解为什么增量有效,而乘法无效。 static_cast<>() 是什么?

如有任何帮助,我们将不胜感激。

I don't fully understand why increment works, where multiply does not.

简短回答:在迭代器上,定义了增量 (++) 运算符,但没有定义乘法。

长答案

对迭代器的操作不是 begin() 位置具有 1 值的代数。

迭代器是指针的演变,指针是一个代表内存中位置的数字,在一阶近似(也是二阶近似,std::vectors)中,您可以将迭代器视为一个指针。

假设 begin() return 1000 并且 Struct_variant 大小是 10(完成的虚构数字)。

使用variant_itr++你增加指针(迭代器)值,也就是说(指针算术)你没有得到1001(1000加1)而是1010,这是后续[=15的位置=].

如果您应用增量 5 次(例如),您会在位置 1050 得到一个指针,而不是 1005。

鉴于这种类型的算术,乘法完全没有意义。

并且未定义。

迭代器或指针相乘没有定义或意义。一个"point in space"不可能是"multiplied",无论是在编程中还是在现实生活中。只能乘distances/spans/quantities。

看起来您只是希望将迭代器前进 index_to_erase 个空格。那是加法

const auto variant_itr = struct_vector.begin() + index_to_erase;

就是这样!

如果您的容器的迭代器确实像指向数据的指针一样简单,那么将其转换为 index_to_erase*sizeof(Struct_variant) 的一些底层指针推进的逻辑已经为您完成。

请注意,这仅适用于随机访问迭代器;更一般地说,您可以使用 std::advancestd::next,但如果您发现自己需要它,那么您的解决方案可能效率不高。