0

So, the goal of the function is to add odd numbers to the array between 1 and a provided integer (inclusive). It seems like a simple task, however, I can't seem to get it to successfully add the integers to the actual array.

void populate(std::vector<int> ary, int a)
{
    for (int i = 1; i <= a; i++)
    {
        if (i % 2 != 0)
        {

            ary.push_back(i);
        }

    }
}

The function itself isn't const, so shouldn't it be adding values to the array successfully?

EDIT: This is all done in a main, so here it is.

int main()
{
    std::vector<int> loli(100);

    populate(loli, 31);


    for (int value : loli)
    {

        std::cout << value << " ";
        system("pause");
    }
}

EDIT 2: I've tried adding a return statement instead, however i still get the result zero.

std::vector<int> populate(std::vector<int> ary, int a)
{
    for (int i = 1; i <= a; i++)
    {
        if (i % 2 != 0)
        {

            ary.push_back(i);
        }

    }
    return ary;
}



int main()
{

    std::vector<int> loli(100);




    for (int value : populate(loli, 31))
    {

        std::cout << value << " ";
        system("pause");
    }



}
Granzo
  • 1
  • 3

1 Answers1

1

Your function should either return the final array after the for loop or you should pass the array as a pointer to the function.

Heapify
  • 2,581
  • 17
  • 17
  • 1
    std::vector populate(std::vector ary, int a) { for (int i = 1; i <= a; i++) { if (i % 2 != 0) { ary.push_back(i); } } return (ary); } like this? – Granzo Sep 28 '17 at 14:04
  • Yes. Without the return statement, your function will not return anything and when you call the function, it will not do anything. Also, When you call the function, you should save the returned value in a variable – Heapify Sep 28 '17 at 14:06