2017-08-25 107 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 
相关问题