如何将向量传递给 func() 并将 return vector[array] 传递给 main func()

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

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]; 
    } 
}

有人可以帮助我理解如何以整个数组的形式将上面的 catcher[i] 传递给 main func() 吗?提前致谢...

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;

你可以这样做:

#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);
}
 

您的 multif() 函数:

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]; 
    } 
}

这将使 catcher 和 return 的第一个元素加倍。我不认为那是你想要的。如果您想将函数中的所有元素加倍,请将其更改为:

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]); 
    } 
}

此外,在 main() 中,您调用 std::cout << multif << std::endl; 将打印 multif() 的内存地址,这也可能不是您想要的。

如果要打印 varray 的所有值,请尝试:

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';
}