c++ - 从c++中的函数返回数组 vector

标签 c++ vector stl

<分区>

我必须从函数返回 vector 。我尝试通过返回值并将其作为引用传递。但我得到垃圾值。 下面的程序给出了以下输出。

 **This is the print inside the function**
 1 7 8  
 1 2 3 
 4 5 6 

 **This is the print using the return value /  referenced value outside the function**. 
 1 7 8 
 46980021526656 46980019425190 0 
 1 46980021526656 6

#include <iostream>
#include<vector>
using namespace std;

void process(vector<unsigned long long int*> &vec)
{
    //vector<unsigned long long int*> vec;
    unsigned long long int a[] ={1,2,3};
    unsigned long long int b[] = {4,5,6};
    vec.push_back(a);
    vec.push_back(b);

    for (int i = 0;i < vec.size();i++)
    {
        for (int j = 0;j < 3;j++)
        {
            cout << vec[i][j] << " ";
        }
        cout << "\n";
        }
    cout << "\n";

//return vec;
}

int main() {
// your code goes here
vector<unsigned long long int*> vec;
unsigned long long int c[] ={1,7,8};
vec.push_back(c);
process(vec);
for (int i = 0;i < vec.size();i++)
{
    for (int j = 0;j < 3;j++)
    {
        cout << vec[i][j] << " ";
    }
    cout << "\n";
}
cout << "\n";
return 0;
}

我不知道哪里出了问题。我提到了许多堆栈溢出帖子。但是我找不到解决方案

请指出我做错了什么。提前致谢

最佳答案

Please do point out what i am doing wrong

您的代码是:

void process(vector<unsigned long long int*> &vec)
{
    //vector<unsigned long long int*> vec;
    unsigned long long int a[] ={1,2,3};
    unsigned long long int b[] = {4,5,6};
    vec.push_back(a);
    vec.push_back(b);

所以 process 记住局部变量 abvec 地址,当你返回 < em>main 这些局部变量不再存在,它们的内容未定义/损坏所以在 main 你写未定义的值

vec.push_back(a); 不复制 a,它只是推送 a

的地址

关于c++ - 从c++中的函数返回数组 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54127637/

相关文章:

c++ - 制作对 inner_product 的自定义调用 (C++ STL)

c++ - 为什么在传递 lambda 而不是函数指针时无法推断模板参数

c++ - 按值传递对象时出现断言错误——这是我的复制构造函数?

c++ - vector<T>::swap 和临时对象

c++ - 无法在类中初始化 unique_ptr 的 vector

c++ - 如何使用 RTTI 确定代码的行为

c++ - 将数据的平均值插入 vector

c++ - 为快速查找优化的有序关联数据结构?

c++ - "Deep"头部依赖分析

c++ - 符合 unicode 且跨平台的 Unbuffer 文件写入