函数中的C ++数组

时间:2011-01-30 21:09:31

标签: c++ arrays iteration

我想将数组发送给函数!

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

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

$test = array(1, 2, 3);
a($test);

3 个答案:

答案 0 :(得分:11)

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

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

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

// 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());

有关详细信息,请考虑自己a good introductory C++ book

答案 1 :(得分:2)

试试这个方法:

int a[3];
a[0]=1;
a[1]=...

void func(int* a)
{
   for( int i=0;i<3;++i )
      printf("%d",a++);
}

答案 2 :(得分:1)

template <typename T, size_t N>
void functionWithArray(T (&array)[N])
{
    for (int i = 0; i < N; ++i)
    {
        // ...
    }
}

void functionWithArray(T* array, size_t size)
{
    for (int i = 0; i < size; ++i)
    {
        // ...
    }
}

第一个使用实际数组,因为在编译时已知数组,所以不需要指定数组的长度。第二个指向一块内存,因此需要指定大小。

这些功能可以两种不同的方式使用:

int x[] = {1, 2, 3};
functionWithArray(x);

int* x = new int[3];
x[0] = 1;
x[1] = 2;
x[2] = 3;
functionWithArray(x, 3);