从c ++中的函数返回数组的向量

ses*_*esh 0 c++ 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;
}
Run Code Online (Sandbox Code Playgroud)

我不知道出了什么问题.我提到了许多堆栈溢出帖子.但我无法找到解决方案

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

bru*_*uno 6

请指出我做错了什么

你的代码是:

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);
Run Code Online (Sandbox Code Playgroud)

所以进程记忆局部变量ab的vec地址,当你回到主要的这些局部变量不再存在时,它们的内容是未定义/坏的所以在main中你写的是未定义的值

vec.push_back(a);不会复制一个,刚推的地址

  • 这个答案绝对正确.在愤怒地投票之前,偷看需要仔细阅读. (6认同)
  • @MateuszGrzejek不,问题是字面上(引用):"请指出我做错了什么" (5认同)