1

I fill vector with random numbers without repeating ones, but when I try to output them, the vector contains only 0s. I tried to clear it before the filling with func .clear() but then the program can't access particular elements in it. When I run the program with debugger it shows that vector contains some numbers, but when it run the func printing() it prints only 0s. I attached screenshots of my tries after code listing.

#include <iostream>
#include <vector>

void filling(std::vector<int> array, int size);
void printing(std::vector<int> array, int size);

int main()
{
    srand(time(0));

    int sizeA;
    printf("Enter size of vector A: ");
    std::cin >> sizeA;
   
    std::vector<int> A (sizeA);    
    filling(A, sizeA);

    printf("Vector A: \n\t");
    printing(A, sizeA);        
}
void filling(std::vector<int> vector, int size)
{
    //filling vector without repeating numbers
    int temp;
    bool flag;
    
    vector[0] = rand() % 31;
    for (int i = 1; i < size; )
    {
        temp = rand() % 31;
        flag = true;
        for (int j = 0; j < size; j++)
        {
            if (vector[j] == temp)
            {
                flag = false;
                break;
            }
            else
            {
                continue;
            }
        }
        if (flag)
        {
            vector[i] = temp;
            i++;
        }
    }
}
void printing(std::vector<int> vector, int size)
{
    for (int i = 0; i < size; i++)
    {
        printf("%d ", vector[i]);
    }
}

This is the result I get but it's not what I expect:

Unwanted result

Elements that debugger shows in vector after filling in the func:

vector after filling

Elements that shows after executing the func filling()

before printing

  • 1
    `void filling(std::vector vector, int size)` you pass the vector by value making a copy and operating on that copy inside the filling function. So in `int main()` the variable `A` is unchanged after filling() ends. – drescherjm Dec 15 '21 at 00:22
  • 1
    You are passing the vectors by value (i.e you are sending a copy of the array to your funciton). Both `filling()` and `printing()` are working on copies of the original. Since you are working on copies the original never changes. Change the functions to take a referecen to the original. – Martin York Dec 15 '21 at 00:22
  • @drescherjm Yes, thanks a lot. It works now! :) –  Dec 15 '21 at 00:39

0 Answers0