繁体   English   中英

在 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<>()?

任何帮助表示赞赏。

乘以迭代器或指针没有定义或意义。 “空间点”不能“乘以”,无论是在编程中还是在现实生活中。 只有距离/跨度/数量可以相乘。

看起来您只是希望通过index_to_erase空间来推进迭代器。 那是加法

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

就是这样!

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

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

我不完全理解为什么增量有效,而乘法无效。

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

长答案

迭代器上的操作不是代数,其中begin()位置具有1值。

迭代器是指针的演变,它是表示内存中位置的数字,在第一次近似(也是第二次近似,使用std::vector s)中,您可以将迭代器视为指针。

假设begin()返回 1000 并且Struct_variant大小为10 (完成的发明数)。

使用variant_itr++增加指针(迭代器)值,即(指针算术),您不会得到 1001(1000 加 1),而是 1010,这是后续Struct_variant的位置。

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

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

并且是未定义的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM