[C++11] 向函數形參傳遞vector的引用,並返回vector

#include<iostream>
#include<iterator>
#include< vector>
using namespace std;
int main() {
    vector<int> v;   
    vector<int> v3;
    vector<int> p(vector<int> &refv);   // 函數聲明
    v3 = p(v);  // 將返回值ref直接賦給v3
    // 輸出v3
    cout << "v3" << endl;
    for (auto it : v3) {
        cout << it << endl;
    }
    // 輸出v
    cout << "v" << endl;
    for (auto it : v) {
        cout << it << endl;
    }
    system("pause");
}

// refv是v的引用,在函數內修改refv,等於對v進行了同樣操作,函數返回值類型爲vector<int>
vector<int> p(vector<int> &refv) {
    refv.push_back(1);
    refv.push_back(2);
    // 輸出refv
    cout << "refv" << endl;
    for (auto it : refv) {
        cout << it << endl;
    }
    return refv;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章