请问用vector作返回值的函数应该怎样写

解决方案 »

  1.   

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    vector<int> ret_vecInt()
    {
    vector<int> vecInt(5, 10);
    return vecInt;
    }void main()
    {
    vector<int> vecIntTemp(5, 10);
    vecIntTemp = ret_vecInt();
    copy(vecIntTemp.begin(), vecIntTemp.end(), ostream_iterator<int>(cout, "\n"));
    }
      

  2.   

    #include <cstdlib>
    #include <cstring>
    #include <string>
    #include <vector>
    #include <iostream>using namespace std;typedef vector<string>  vector_str;vector_str * split_str(const char *str, const char *splitter)
    {
        vector_str * p_vector = new vector_str;
        
        char * token;
        char * buff = new char[strlen(str) + 1];
        strcpy(buff, str);
        token = strtok(buff, splitter);
        while (token != NULL) {
            p_vector->push_back(token);
            token = strtok(NULL, splitter);
        }
        
        delete[] buff;    
        return p_vector;
    }int main(int argc, char *argv[])
    {
        vector_str * v1 = split_str("aa:bb:cc:dd", ":");
        vector_str::iterator Iter;
        
        for (Iter = v1->begin(); Iter != v1->end(); Iter++) {
            cout << *Iter << ' ';
        }
        
        delete v1;
        
        system("PAUSE");
        return 0;
    }
      

  3.   

    返回指针需要在外面释放的,如果调用者不是写这个函数的人容易忘记释放
    比较好的做法是传vector 引用进入函数,