函数中的C++数组

mrd*_*iri 1 c++ arrays iteration

我想将一个数组发送给一个函数!

我是一个php程序员,所以我在php中编写一个例子,请将其转换为C++:

function a($x) {
    foreach ($x as $w) print $w;
}

$test = array(1, 2, 3);
a($test);
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 11

执行此操作的最佳方法是使函数采用一对迭代器:一个到范围的开头,一个到范围的结尾(实际上是"一个结束"的范围):

template <typename ForwardIterator>
void f(ForwardIterator first, ForwardIterator last)
{
    for (ForwardIterator it(first); it != last; ++it)
        std::cout << *it;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以用任何范围调用这个函数,无论该范围来自数组,字符串还是任何其他类型的序列:

// You can use raw, C-style arrays:
int x[3] = { 1, 2, 3 };
f(x, x + 3);

// Or, you can use any of the sequence containers:
std::array<int, 3> v = { 1, 2, 3 };
f(v.begin(). v.end());
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请考虑为自己准备一本好的C++入门书.