C ++ structure behavior
I am trying to improve my knowledge of the C ++ language and am building a stack of stacks. Below is a very short example of my question: Why do I need to access structure members directly to modify them, rather than using functions to do so? If anyone knows why this is the case, then an answer is greatly appreciated! Thanks to
#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;
}
source to share
stacks.getStackAtIndex(0)
returns a copy of the first Stack
, while
stacks.stacks[0]
returns a link to it. (cf std :: vector :: operator [] ).
You can fix this by changing the return type getStackAtIndex
to link Stack
:
Stack& getStackAtIndex(int i) {
return stacks[i];
}
source to share
You return a copy of the stack at [i] when you call
Stack Stacks::getStackAtIndex(int i);
this means that you are not actually working on the stack at that index, but a completely new one, which is created by copying data from the required stack. Just change the return value from
Stack
to
Stack&
Also try not to use the std namespace, you will be surprised at how many things you actually use in that namespace. It can overwhelm you if you ever have to avoid using it.
Also, I noticed that you used
int N;
both item in Stack and parameter in
void Stack::add(int);
I would change that.
source to share