-6

I have an issue with my code, I can fill the table but when I display it, it display 0 for me, here is my code

#include<iostream>
#include<vector>

using namespace std;
int n;
void lire_tab(vector<int> A);
void tri_tab(vector<int> A);
void aff_tab(vector<int> A);

int main()
{        
    cout<<"donnez la taille du tableau: ";
    cin>>n;
    vector<int> A(n);
    lire_tab(A);
    aff_tab (A);
    tri_tab (A);
    aff_tab (A);

    return 0;
}

void lire_tab(vector<int> A)
{
    for(int i=0;i<n;i++)
    {
        cout<<"A["<<i<<"]= ";
        cin>>A[i];
    }
    cout<<"________________________"<<endl;
}

void tri_tab(vector<int> A)
{
    int temp;
    temp=0;
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++){
            if(A[i]<A[j])
            {
                temp   = A[i];
                A[i]   = A[j];
                A[j] = temp;
            }
        }        
    }
}

Can you help me please, I'm really lost in this, I don't really figure out why it print 0

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
kichkich
  • 19
  • 1
  • 4
  • 1
    You need to pass the vector by reference. ie `void lire_tab(vector A) => void lire_tab(vector& A)` – NathanOliver Jan 22 '16 at 17:13
  • a comment about program structure: Try to write your functions so they are more general and transportable. Ask "why should `lire_tab` care that the variable used to hold the user's input was named `n`?" A vector can tell you it's size, so the `int n;` should be local to `main()` - you only use it to declare the vector. After that, in the functions, use `A.size()` in your `for` statements. – PMorganCA Jan 22 '16 at 17:47

2 Answers2

2

Your functions are using passing by value, therefore, a copy is seen within the function.

Please read about passing by reference

void lire_tab(vector<int>& A);
Dongxu Li
  • 46
  • 1
1

Instead of accepting the vector by value

void lire_tab(vector<int> A)

You want to accept the vector by reference

void lire_tab(vector<int>& A)

Otherwise you are only modifying a function-local copy of your vector, not the original vector that was passed in.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218