Aldomond
Aldomond

Reputation: 171

Returning a structure from a function

I am trying to learn structures, but I am confused why I can't see changes in the structure after returning it from my function.

#include <iostream>
#include <vector>

using namespace std;

struct multiset {
    vector <int> elements;
    vector <int> counts;
};

multiset multiset_add(multiset Set, int num) {
     Set.elements.push_back(num);
     return Set;
}

int main()
{
    multiset Set;
    multiset_add(Set, 2);
    cout << Set.elements[0];
    return 0;
}

If I would add the cout << Set.elements[0] inside the function after pushing a number into the set, it would print 2, but It won't print 2 after returning it, why is that?

Upvotes: 0

Views: 70

Answers (2)

TheEagle
TheEagle

Reputation: 5992

Your main function should be like this to work the way you designed it:

int main()
{
    multiset Set;
    Set = multiset_add(Set, 2);
    cout << Set.elements[0];
    return 0;
}

In your original code, you are never using the return value of multiset_add !

But, in fact, you should rather use pointers to not create a copy of your set.

Upvotes: 2

Tom Gebel
Tom Gebel

Reputation: 805

Your function

multiset multiset_add(multiset Set, int num) {
     Set.elements.push_back(num);
     return Set;
}

gets the parameter Set passed by value. You either have to use the returned multiset in you main function like this:

int main()
{
    multiset Set;
    Set = multiset_add(Set, 2);
    cout << Set.elements[0];
    return 0;
}

Or you can pass the parameter by reference, so it can be modified inside the function like this:

void multiset_add(multiset& Set, int num) {
     Set.elements.push_back(num);
}

A raw pointer would also be possible, but a reference is the preferrable option.

Upvotes: 3

Related Questions