我知道iterator可以用于vectorwithstd::vector::begin或 withstd::begin中定义的<iterator>。对于 也一样std::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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我认为我可以做到这一点,因为他们在 C++ 入门中使用了这段代码begin,并end让迭代器到达第一个和最后一个元素:
#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;
}
Run Code Online (Sandbox Code Playgroud)
是的,迭代器可以用在数组上。例如
int main()
{
int arr[] = {9, 18, 31, 40, 42};
for (auto cbeg = cbegin(arr); cbeg != cend(arr); ++cbeg) {
cout << *cbeg << endl;
}
Run Code Online (Sandbox Code Playgroud)
将打印 的所有元素arr。
问题是,您的print()函数接受指针,因此在这种情况下不能使用迭代器。
但是,如果您更改print()为
void print(int(&arr)[5])
{
// same body as before
}
Run Code Online (Sandbox Code Playgroud)
或(如果您不希望大小固定为5)
template<int N> void print(int(&arr)[N])
{
// same body as before
}
Run Code Online (Sandbox Code Playgroud)
您会发现它可以工作,因为数组是通过引用传递的。请注意,如果将指针传递给这些函数,它们将无法编译。