【问题标题】:How to pass vector to func() and return vector[array] to main func()如何将向量传递给 func() 并将向量 [array] 返回给主 func()
【发布时间】:2021-12-10 23:15:20
【问题描述】:
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;

【问题讨论】:

  • 你的教科书告诉你关于调用函数并获取它返回的值?
  • 伙计,我没有教科书,我刚开始学习编码:(
  • 你绝对应该投资textbook
  • catcher[i] 不是“整个数组”,它是单个 int。从字面上理解你的问题,它几乎听起来像协程,但我认为你想要更简单的东西
  • Here's a list of decent books。你真的需要投资几本初学者书籍,甚至可能需要上课。否则很难学到任何有用的东西(在线资源通常是不够的,有时可能会直接有害)。

标签: c++ vector func


【解决方案1】:

您的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 的第一个元素加倍并返回它。我不认为那是你想要的。如果要将函数中的所有元素加倍,请将其更改为:

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 &lt;&lt; multif &lt;&lt; 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';
}

【讨论】:

  • 'for(const auto &i : varray) std::cout
  • 这是一个基于范围的 for 循环。如果你想有一个好的教程但又不想花钱买书,我推荐this网站。它吸收了很多好的实践,在本教程的后面,你会知道我的“酷”循环是什么。
【解决方案2】:

你可以这样做:

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

【讨论】:

  • OP 的代码已经通过引用传递向量参数。
  • 我现在看到了...,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 2014-08-09
相关资源
最近更新 更多