简体   繁体   English

如何在 constexpr function 中使用 reverse_iterator

[英]How to get around using a reverse_iterator within a constexpr function

I have a prepopulated std::vector<uint64_t> that I am passing to my constexpr function by constant reference and another std::vector<uint64_t> that I'm passing by reference to be populated with values.我有一个预填充的std::vector<uint64_t>我通过常量引用传递给我的constexpr function 和另一个我通过引用传递的std::vector<uint64_t>以填充值。

I want to calculate the distance between each element in the collection vector below and store the results into the distances vector.我想计算下面collection向量中每个元素之间的距离,并将结果存储到distances向量中。 In other words, I want to take the value at index 1 and subtract it from the value at index 0 then store that into the other vector, and so on.换句话说,我想取索引 1 处的值并从索引 0 处的值中减去它,然后将其存储到另一个向量中,依此类推。

I was thinking of using either reverse_iterator or const_reverse_iterator to help with this process...我正在考虑使用reverse_iteratorconst_reverse_iterator来帮助这个过程......

constexpr void euclidean_distance(const std::vector<uint64_t>& collection, std::vector<uint64_t> distances ) {
    auto It1 = collection.rbegin();   // fails to compile
    auto It2 = collection.crbegin();  // fails to compile

    // ... code to do the calculation...
}

However, within Visual Studio 2017 both of these fail to compile as they are not a literal type...但是,在 Visual Studio 2017 中,这两个都无法编译,因为它们不是文字类型......

What options do I have to achieve a similar functionality?我有什么选择来实现类似的功能?

There are too many issues here, and I can't tell which is the problem...这里的问题太多了,我不知道是哪个问题...

In C++, constexpr means that the value must be available at compile time.在 C++ 中,constexpr 表示该值必须在编译时可用。 const, on the other hand, just means the data is unchangeable.另一方面,const 只是意味着数据是不可更改的。

Don't use constexpr here.不要在这里使用 constexpr 。 It makes no sense.这没有道理。 In fact, even having your function return const makes no sense, void functions don't return anything.事实上,即使让你的 function 返回 const 也没有意义,void 函数也不会返回任何东西。 and should not be qualified by const or constexpr under any circumstances.并且在任何情况下都不应由 const 或 constexpr 限定。 constexpr functions are for cases where you want to evaluate computations between primitive data types (ie, int, float, char) at compile time. constexpr 函数适用于您希望在编译时评估原始数据类型(即 int、float、char)之间的计算的情况。 and the inputs must also be constexpr.并且输入也必须是 constexpr。

primes isn't listed here, by the way...is it a typo?顺便说一下,这里没有列出primes ……是错字吗?

You shouldn't be initializing.crend() to anything in the first place, by the way.顺便说一句,你不应该首先将 initializing.crend() 设置为任何东西。 You should use.crbegin() instead.您应该改用 .crbegin() 。

const std::vector<uint64_t>& is not a const reference, it's a reference to a const vector. const std::vector<uint64_t>&不是 const 引用,它是对 const 向量的引用。 And technically, all references are const...从技术上讲,所有引用都是常量...

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

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