-2

Please find my below code.I want to know whether we can pass an array through a function which is accepting vector. If yes please tell me how.

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);
Naseer Mohammad
  • 389
  • 4
  • 14
  • 9
    No. Where is the vector? – Ron Aug 25 '17 at 11:40
  • 4
    `int fs[N];` is illegal in standard C++ (without compiler extensions) as `N` must be known at compile time instead of runtime. Switch to a `std::vector` if you need runtime sized arrays – Cory Kramer Aug 25 '17 at 11:41
  • 1
    `int tfs[]=fs;` You can't copy arrays like this. Didn't your compiler tell you so? Also why don't you use a `std::vector` in 1st place? – user0042 Aug 25 '17 at 11:43
  • @Ron that is the reason why i have given ???? as parameter to my function because i dont know how to pass – Naseer Mohammad Aug 25 '17 at 11:51
  • @user0042 Because i dont know using vectors I am new to C++ – Naseer Mohammad Aug 25 '17 at 11:53
  • 4
    In that case I suggest you take a look at the [std::vector](http://en.cppreference.com/w/cpp/container/vector) or even better read one of these [fine C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Ron Aug 25 '17 at 11:53
  • _@Naseer_ Do just as @Ron said. – user0042 Aug 25 '17 at 12:11

1 Answers1

0

I've made some modifications to your code to help you get started. Furthermore, I recommend taking a look at http://www.cplusplus.com/reference/vector/vector/ for a high-level overview of std::vector and the functionalities it provides.

#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
AZhu
  • 28
  • 1
  • 7