Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ struct behavior

Tags:

c++

struct

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;
}
like image 289
Tomas Gudmundsson Avatar asked Apr 16 '26 19:04

Tomas Gudmundsson


1 Answers

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];
}
like image 144
Torbjörn Avatar answered Apr 19 '26 10:04

Torbjörn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!