Home > Net >  How to pass vector to func() and return vector[array] to main func()
How to pass vector to func() and return vector[array] to main func()

Time:10-26

int multif(std::vector<int> &catcher)
{
    printf("\nThe array numbers are:  ");
    for (int i = 0; i < catcher.size(); i  )
    {
        catcher[i]*=2;
        //printf("%d\t", catcher[i]);
        return catcher[i]; 
    } 
}

Can someone help me to understand how to pass above catcher[i] to main func() in the form of entire array? Thanks in advance...

int main()
{
    std::vector <int> varray;
    while(true)
    {
        int input;
        if (std::cin >> input)
        {
            varray.push_back(input);
        }
        else {
            break;
        }
    }
    multif(varray);

    std::cout << multif << std::endl;

CodePudding user response:

You could do it like this :

#include <vector>
#include <iostream>


void multif(std::vector<int>& catcher) 
{
    std::cout << "\nThe array numbers are: ";
    for (int i = 0; i < catcher.size(); i  )
    {
        catcher[i] *= 2;
        std::cout << catcher[i] << " ";
    }
}

int main()
{
    // use initializer list to not have to test with manual input
    std::vector<int> input{ 1,2,3,4,5 }; 
    multif(input);
}
 

CodePudding user response:

Your multif() function:

int multif(std::vector<int> &catcher)
{
    printf("\nThe array numbers are:  ");
    for (int i = 0; i < catcher.size(); i  )
    {
        catcher[i]*=2;
        //printf("%d\t", catcher[i]);
        return catcher[i]; 
    } 
}

This will double the first element of catcher and return it. I don't think that's what you want. If you want to double all the elements in your function, change that to:

void multif(std::vector<int> &catcher)
{
    printf("\nThe array numbers are:  ");
    for (int i = 0; i < catcher.size(); i  )
    {
        catcher[i]*=2;
        //printf("%d\t", catcher[i]); 
    } 
}

Also, in main() , you call std::cout << multif << std::endl; which will print the memory address of multif(), which also probably not what you want.

If you want to print all the values of varray, try:

void multif(std::vector<int> &catcher)
{
    printf("\nThe array numbers are:  ");
    for (int i = 0; i < catcher.size(); i  )
    {
        catcher[i]*=2;
        //std::cout << catcher[i] << '\n' you can print it here, or:
    } 
}

int main()
{
    std::vector <int> varray;
    while(true)
    {
        int input;
        if (std::cin >> input)
        {
            varray.push_back(input);
        }
        else {
            break;
        }
    }
    multif(varray);
    
    for(const auto &i : varray) std::cout << i << '\n';
}
  • Related