2017-08-25 106 views
-2

請查看我的下面的代碼。我想知道我們是否可以通過接受向量的函數傳遞數組。如果是,請告訴我如何。是否可以將數組傳遞到C++中的向量中

int main() 
{ 
    int N,M,i; 
    cin>>N>>M; 
    int fs[N]; 
    for(i=0;i<N;i++){ 
     cin>>fs[i]; 
    } 
    int K=findK(fs,M); 
    cout << "Hello World!" << endl; 
    return 0; 
} 
int findK(????,int M){ 
    int b_sz,no_b; 
    int tfs[]=fs; 
    make_heap(tfs); 
+9

No.矢量在哪裏? – Ron

+4

'int fs [N];'在標準C++(無編譯器擴展)中是非法的,因爲在編譯時必須知道'N'而不是運行時。如果你需要運行時大小的數組,則切換到'std :: vector' – CoryKramer

+1

'int tfs [] = fs;'你不能像這樣拷貝數組。你的編譯器不是這樣告訴你的嗎?還有,爲什麼你不在第一個地方使用'std :: vector'? – user0042

回答

0

我已經對您的代碼進行了一些修改以幫助您入門。此外,我建議查看http://www.cplusplus.com/reference/vector/vector/以瞭解std :: vector的高級概述及其提供的功能。

#include <iostream> 
#include <vector> 

using namespace std; 

int findK(const vector<int> &fs, int M); // Function stub so main() can find this function 

int main() 
{ 
    int N, M, i; // I'd recommend using clearer variable names 
    cin >> N >> M; 
    vector<int> fs; 

    // Read and add N ints to vector fs 
    for(i = 0; i < N; i++){ 
     int temp; 
     cin >> temp; 
     fs.push_back(temp); 
    } 

    int K = findK(nums, M); 
    cout << "Hello World!" << endl; 
    return 0; 
} 

int findK(const vector<int> &fs, int M){ // If you alter fs in make_heap(), remove 'const' 
    make_heap(fs); 

    // int b_sz,no_b; // Not sure what these are for... 
    // int tfs[]=fs; // No need to copy to an array 
    // make_heap(tfs); // Per above, just pass the vector in 
相關問題