gpt4 book ai didi

c++ - array_view 的指针运算

转载 作者:行者123 更新时间:2023-11-30 01:12:53 25 4
gpt4 key购买 nike

我刚刚看过 Herb Sutter 的“默认情况下编写良好的 C++14...”(https://www.youtube.com/watch?v=hEx5DNLWGgA)的第一部分,我有一个(可能是愚蠢的)关于 array_view 的问题。

目前的情况是发送一个 array_view 而不是指针和长度以避免指针运算,但是 array_view 如何处理这样的情况:

int vec[10];
func(vec+2, 5); //start from the 2nd element and process 5 of them

array_view 是否支持这种东西,或者我只是弄错了用例?

最佳答案

首先可以得到the slides来自 cppcon's Github repo .

正如您在#8#10 中看到的,您可以编写以下内容:

Run It Online !

// http://llvm.org/apt/
// sudo apt-get install clang-3.6 lldb-3.6 libc++-dev libc++abi-dev
// clang-3.6 -stdlib=libc++ -std=c++14 main.cpp -lc++ -lc++abi

#include <array>
#include <vector>
#include "array_view.h" // https://github.com/Microsoft/GSL

void func(gsl::array_view<int> av)
{
// ...
}

int main()
{
{
int vec[10];
func(vec);
//func(vec, 5); // syntax error (func expects exactly 1 argument)
func({vec, 5}); // notice the curly braces
func({vec+2, 5});
}

{
std::vector<int> vec;
func(vec);
}

{
size_t len = 10;
int* p = new int[10];
func({p,len});
// remember to delete[] p
}

{
std::array<int, 2> arr;
func(arr);
}
}

这是有道理的。如果你看array_view.h ,您将看到所有 array_view 的构造函数:

constexpr array_view(pointer ptr, bounds_type bounds)
constexpr array_view(T * const & data, size_type size)
constexpr array_view(T(&arr)[N], size_type size)
constexpr array_view (const std::array<std::remove_const_t<value_type>, N> & arr)
// ...

关于c++ - array_view 的指针运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33275767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com