简体   繁体   中英

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;
}
stacks.getStackAtIndex(0)

returns a copy of the first Stack , while

stacks.stacks[0]

returns a reference to it. (cf 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];
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM