-2

So I'm writing some code and want to display the contents of a structure but after creating a pointer to put as the first element of the vector. When I have the program display the first element of the vector, it comes up blank. Any thoughts on what I'm doing wrong?

struct Account
{
    string name;
    double balance;
    int acctNumber;
};

void create_Account(vector<Account> &accts);

int main()
{
    vector<Account> accts(1);

    create_Account(accts);

    return 0;
}

void create_Account(vector<Account> &accts)
{
    Account account;

    cout << "Name: ";
    cin >> account.name;
    cout << "Balance: ";
    cin >> account.balance;
    cout << "Account No: ";
    cin >> account.acctNumber;

    accts.push_back(account);

    cout << endl;
    cout << "Name: " << accts[0].name << endl;
}
  • Why are you using `Account *acctptr` as a parameter? – drescherjm Jul 05 '19 at 22:21
  • Why does create_Account do this `acctptr = new Account;`? – drescherjm Jul 05 '19 at 22:23
  • 1
    You are passing the vector by value. This is not C#/Java, don't use `new` lightly and please read on value semantics. There's a curated list of [good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) that might come handy. – Quimby Jul 05 '19 at 22:23
  • Sorry you guys had to deal with my idiotic code... I'm only a beginner... I can't really explain why I did what I did. – LastPotato Jul 05 '19 at 22:28
  • I just want to know if there is a way to display structure contents from a vector – LastPotato Jul 05 '19 at 22:29
  • ***I just want to know if there is a way to display structure contents from a vector*** Yes of course this is possible. However you need to fix the bugs we mentioned before doing that. – drescherjm Jul 05 '19 at 22:30
  • The reason for the `new` is because I was going to have this process repeated. That was my thought process for involving `new` – LastPotato Jul 05 '19 at 22:34
  • `acctptr = new Account;` is not needed and actually causes a bug (memory leak). Use `Account account;` instead and no usage of pointers or new. – drescherjm Jul 05 '19 at 22:35
  • You don't want `new` at all. – drescherjm Jul 05 '19 at 22:35
  • But isn't the way to store multiple structures within a vector to create pointers for each structure? Or is it another way. – LastPotato Jul 05 '19 at 22:38
  • 1
    Again, you don't need `new` here. Just do `Account account;`, and then `accts.push_back(account);`. – HolyBlackCat Jul 05 '19 at 22:44
  • Okay, resolved the issue with `new`. – LastPotato Jul 05 '19 at 22:47

1 Answers1

1

The reason it comes up blank is that vector<accounts> accts(1); creates a vector with one element. That element is default constructed, so it’s name member is blank. The code in createAccount adds a second account, which is at accts[1]. accts[0].name is still blank.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165