如果元素在向量中向后推回是有效的吗? [英] If the elements push back in the vector are valid?

查看:87
本文介绍了如果元素在向量中向后推回是有效的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

void add (vector<int> & a )
{
    for(int i=0;i<=9;i++)

        a.push_back(i);

}



int main()

{

    vector <int> a;
    add(a);
}









这些元素有效吗?<当函数添加结束时,它们是免费的吗?





are these elements valid?
will they be free when the function add end?

推荐答案





add()函数中插入的元素在函数 add()结束后有效。这是因为,向量是 main()函数的局部变量,在 add()函数中,您只能引用它。



因此,您可以在 add()电话后立即将所有元素写入控制台:

Hi,

the elements that you inserted in the add() function will be valid after the function add() ends. It is because, the vector is a local variable of the main() function and in the add() function you only reference it.

For this reason, you can write all the elements to the console just after the add() call:
#include<vector>
#include<iostream>
#include<stdio.h>
using std::vector;

void add (vector<int> & a )
{
    for(int i=0;i<=9;i++)
        a.push_back(i);
}
 
int main()
{
    vector<int> a;
    add(a);
    
    // write all the lements
    for (vector<int>::iterator it = a.begin(); it != a.end(); it++)
    {
        printf("Element: %d\n", *it);
    }
}



main()函数结束时向量< int> a< / int> vill停止有效并且所有元素都被销毁。这是因为 vector< int> a< / int> main()函数的局部变量。



希望它有所帮助。



祝你好运,

JK


In the moment when the main() function ends The vector <int> a</int> vill stop being valid and all the elements are destroyed. It is because the vector<int> a</int> is a local variable of the main() function.

Hope it helps.

Best regards,
J.K.


这篇关于如果元素在向量中向后推回是有效的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆