开发者

C++ array in function

开发者 https://www.devze.com 2023-02-07 19:21 出处:网络
I want to send a array to a function! I\'m a php programmer, so I write an example in php, and please convert it to C++:

I want to send a array to a function!

I'm a php programmer, so I write an example in php, and please convert it to C++:

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

$tes开发者_C百科t = array(1, 2, 3);
a($test);


The best way to do this is to have the function take a pair of iterators: one to the beginning of the range and one to the end of the range (which is really "one past the end" of the range):

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

then you can call this function with any range, whether that range is from an array or a string or any other type of sequence:

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

For more information, consider getting yourself a good introductory C++ book.


Try this method:

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

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


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

or

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

The first one uses an actual array and the length of the array does not need to be specified since its known at compile time. The second one points to a block of memory so the size needs to be specified.

These functions can be used in two different ways:

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

and:

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

精彩评论

暂无评论...
验证码 换一张
取 消