Tomas Gudmundsson
Tomas Gudmundsson

Reputation: 223

C++ struct behavior

I'm trying to improve my knowledge of the C++ language and am making a stack of stacks. Below is a very short example of my question: why do I have to directly access the members of the struct in order to change them instead of using functions to do that? If anyone knows why this happens a answer is very appreciated! Thanks

#include <iostream>
#include <vector>
using namespace std;

struct Stack {
    int N;
    vector<int> stack;

    int len() { return stack.size(); }

    void add(int N) { stack.push_back(N); }
};

struct Stacks {
    vector<Stack> stacks;

    Stack getStackAtIndex(int i) { return stacks[i]; }

    void addStack(Stack stack) { stacks.push_back(stack); }

    void printStacks() {
            cout << "Printing stacks" << endl;

            for (int i = 0; i < stacks.size(); i++) {
                    cout << "Stack #" << i << ": ";
                    for (int j = 0; j < stacks[i].len(); j++) {
                            cout << stacks[i].stack[j];
                            if (j != stacks[i].len()-1) cout << " -> ";
                    }   
                    cout << endl;
            }   
    }   
};

int main() {

    Stacks stacks;
    Stack stack;
    stack.add(1);
    stacks.addStack(stack);

    // This does not work:
    // stacks.getStackAtIndex(0).add(2);

    // This works:
    stacks.stacks[0].stack.push_back(2);

    stacks.printStacks();

    return 0;
}

Upvotes: 3

Views: 173

Answers (2)

Nathan Krone
Nathan Krone

Reputation: 63

You are returning a copy of the stack at [i] when you call

Stack Stacks::getStackAtIndex(int i);

this means you aren't actually operating on the stack at that index but a completely new one that is constructed by copying the data from the stack you want. Just change the return value from

Stack

to

Stack&

Also try not to use namespace std, you will be surprised how many things you use are actually in that namespace. It may overwhelm you if you are ever forced to avoid using it.

Additionally i have noticed you used

int N;

as both a data member in Stack and a parameter in

void Stack::add(int);

i would change this.

Upvotes: 2

Torbj&#246;rn
Torbj&#246;rn

Reputation: 5820

stacks.getStackAtIndex(0)

returns a copy of the first Stack, while

stacks.stacks[0]

returns a reference to it. (c.f. std::vector::operator[]).

You can fix this by changing the return type of getStackAtIndex to a reference of Stack:

Stack& getStackAtIndex(int i) {
  return stacks[i];
}

Upvotes: 6

Related Questions