2011-01-30 61 views
1

我想发送一个数组到一个函数!函数中的C++数组

我是一个PHP程序员,所以我用PHP编写的例子,并请其转换为C++:

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

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

回答

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

+1:特别是对于最后一句话。如果通过实验进行探索,C++可能会变成一场噩梦。你确定链接是正确的吗?它指向boost :: bind。 – 6502 2011-01-30 21:20:29

+0

@ 6502:糟糕!感谢您的提醒。复制粘贴失败。 – 2011-01-30 21:21:45

2

尝试此方法:

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

void func(int* a) 
{ 
    for(int i=0;i<3;++i) 
     printf("%d",a++); 
} 
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);