注册 登录
编程论坛 C++教室

关于返回vector

y605302737 发布于 2013-06-19 19:40, 487 次点击
大家好,请教下如何返回一个vector类,我知道运行完read函数后,vector<float> arr_name的内存会释放掉,那我怎么写才对这个程序,另外我想读取的txt文件,我不知道文件中数据的数目,用while来判断是否读到文件尾这种方法行吗?
谢谢大家 !!
程序代码:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
vector<float> read(string name);

int main()
{
   
    vector<float> abc;
    yxz = read("yyy.txt");
    vector<float>::iterator p;
    for(p=yyy.begin();p!=yyy.end();p++)
    {
        cout<<"p =="<<*p<<endl;
     
    }

    return 0;
}

vector<float> read(string name)
{
    vector<float> arr_name;
    ifstream fin;
    fin.open("name");
    float value;
    while(!fin.eof())
    {
        fin>>value;
        cout<<"value =="<<value<<endl;
        arr_name.push_back(value);
    }
    fin.close();
    return arr_name;
}
   

 
2 回复
#2
y6053027372013-06-19 21:09
错误已改正,但还是有个问题要问下,为什么返回的arr_name在函数外还会存在,不是出在函数read后它的内存会被释放掉吗??请高手指点。
#3
rjsp2013-06-20 08:36
错误和陋习很多
程序代码:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;

vector<double> read( const char* name );

int main()
{
    vector<double> abc = read("yyy.txt");
    for( vector<double>::const_iterator itor=abc.begin(); itor!=abc.end(); ++itor )
    {
        cout << "p == " << *itor << endl;
    }

    return 0;
}

vector<double> read( const char* name )
{
    vector<double> arr_name;

    ifstream fin( name );
    for( double value; fin>>value; )
    {
        arr_name.push_back( value );
    }
    fin.close();

    return arr_name;
}

还可以
程序代码:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <iterator>
using namespace std;

int main()
{
    // 将文件 yyy.txt 的内容读进 vector<double> abc 中
    vector<double> abc( istream_iterator<double>(ifstream("yyy.txt")), istream_iterator<double>() );

    // 将 vector<double> abc 的内容输出到输出设备上
    copy( abc.begin(), abc.end(), ostream_iterator<double>(cout,"\n") );

    return 0;
}

1