Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 2 questions here... I am writing out a function where it takes in a vector and it is suppose to return as array... Suppose arrs are '0 1 2'.....

1. Is this the correct way to do so?

2. Then now I had wanted to add in an additional element ( eg. arrs.push_back(55) ) within the returnArr function, using the code I have wrote, for this 'adding', do I put it before or after the for-loop? I asked this, because I seems to get different result

Pardon the simple language I used as I am still a beginner in C++

What I have tried:

C++
int * returnArr ( vector<int> arrs )
{        
    cout << "[ " ;
    
    for (int i = arrs.size() - 1 ; i >= 0 ; i--)
    {
        cout << i << " ";
    } 

    cout << "]" << endl;
    
    // Results : [ 2 1 0 ]

}
Posted
Updated 18-Mar-16 0:19am
Comments
Richard MacCutchan 18-Mar-16 5:31am    
No that is not, as far as I can guess, the correct way. What exactly are you trying to do, display the contents of the vector, or convert it to an array that you return from the function?
xenas19 18-Mar-16 5:39am    
The function (where it accepts vector as an argument) should return/output as an array

Try the following:
C++
int* returnArr (vector<int>* arrs)
{
    int i;
    // create an array one larger than the number of elements in the vector
    int* pArray = new int[arrs->size() + 1];
    cout << "[ " ;
    for (i = 0; i << (int)arrs->size(); ++i)
    {
        pArray[i] = arrs->at(i);  // copy the vector value to the array
        cout << pArray[i] << ", ";
    }
    pArray[i] = -1;		// put a termination marker at the end of the array
    cout << " ]" << endl;
    
    return pArray; // return the array to the caller
}


[edit]
Trying to fix what the stupid markdown processor has messed up
[/edit]
 
Share this answer
 
v2
The correct way is returning the vector and using its data[^] member when you need to access the raw pointer.
 
Share this answer
 
There are several things on which I wish to comment.

1. Do not pass the vector parameter as pass by value.
Right way - (const vector<int>& arrs)

2. You could reverse the vector in-place in which case you need to remove the const in point 1.
std::reverse(arrs.begin(), arr.end());

3. You also could copy values to another vector by reversing it.
This way you can simply return the newly created vector.
vector<int> returnArr(const vector<int>& arrs)
{
    vector<int> arrs2(arrs.size());
    std::copy(arrs.rbegin(), arrs.rend(), arrs2.begin());
    return arrs2;
}


4. This is another way to display the vector contents in reverse order.
std::copy(arrs.rbegin(), arrs.rend(), ostream_iterator<int>(cout, " "));
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900