是否可以在 C 数组中使用迭代器?

Is it possible to use iterator in C array?

本文关键字:迭代器 数组 是否      更新时间:2023-10-16

我知道iterator可以用于vector,无论是std::vector::begin还是<iterator>中定义的std::beginstd::end也一样。 我也可以将迭代器与 C 数组一起使用吗?我尝试了以下方法,但没有用。

#include <iostream>
#include <iterator>
using std::cin;
using std::cout;
using std::endl;
using std::begin;
using std::end;
void print(const int *arr) {
for (auto cbeg = cbegin(arr); cbeg != cend(arr); ++cbeg) {
cout << *cbeg << endl;
}
}
int main() {
int arr[] = {9, 18, 31, 40, 42};
print(arr);
}

编辑:

我认为我可以这样做,因为C++入门中的这段代码,他们使用beginend让迭代器首先通过结束元素:

#include <iterator>
using std::begin; using std::end;
#include <cstddef>
using std::size_t;
#include <iostream>
using std::cout; using std::endl;
// const int ia[] is equivalent to const int* ia
// size is passed explicitly and used to control access to elements of ia
void print(const int ia[], size_t size) 
{
for (size_t i = 0; i != size; ++i) {
cout << ia[i] << endl;
}
}
int main() 
{
int j[] = { 0, 1 };  // int array of size 2
print(j, end(j) - begin(j));  
return 0;
}

是的,迭代器可以在数组上使用。 例如

int main()
{
int arr[] = {9, 18, 31, 40, 42};
for (auto cbeg = cbegin(arr); cbeg != cend(arr); ++cbeg) {
cout << *cbeg << endl;
}

将打印arr的所有元素。

问题是,您的print()函数接受指针,因此在这种情况下不能使用迭代器。

但是,如果您将print()更改为

void print(int(&arr)[5])
{
// same body as before
}

或(如果您不希望大小固定为5)

template<int N> void print(int(&arr)[N])
{
// same body as before
}

你会发现它会起作用,因为数组是通过引用传递的。 请注意,如果将指针传递给这些函数,则不会编译这些函数。

您可以在 c 样式数组上使用std::beginstd::end。 不能在指针上使用它们。 C 样式数组在传递给函数时衰减为指针,除非您通过引用传递它们。 动态数组(由 new 分配)也通过指针访问,因此这也不起作用。

void print(int (&arr)[5]) {...}这样的引用传递应该有效。 请注意,如果您想要可变大小的数组,则需要模板。

你似乎在寻找

// use array pointer to dodge array decay of function parameters:
void obfuscated_meta_programming (int (*arr)[5]) 
{ 
for(auto it = std::begin(*arr); it != std::end(*arr); it++)
{
cout << *it << endl;
}
}
int main() 
{
int arr[] = {9, 18, 31, 40, 42};
obfuscated_meta_programming(&arr);
}

可以像这样以理智的方式重写:

void print (int arr[5]) 
{
for(size_t i=0; i<5; i++)
{
cout << arr[i] << endl;
}
}
int main() 
{
int arr[] = {9, 18, 31, 40, 42};
print(arr);
}

不是这样。您的函数print只获得const int *指针。这个指针没有关于函数 mainarr[]数组长度的信息,所以如果你有指向 int 的指针作为参数,那么即使理论上,你也无法迭代函数"print",无论你是否使用迭代器。一种方法是使用 std::array 并使用 char[] 初始化它,如下所示:

#include <iterator>
#include <iostream>
#include <array>
using std::cin;
using std::cout;
using std::endl;

template<size_t N> void print(std::array<int,N> &arr) {
for (const auto &s : arr) {
cout << s << endl;
}
}
int main() {
std::array<int,5> arr = {9, 18, 31, 40, 42};
print(arr);
}

编译 --std=c++11

C 数组没有长度前缀。如果你有大小,你可以创建一个满足Iterator要求的指针:

begin = arr;
end = arr + size;
some_algorithm(begin, end);