简体   繁体   中英

What are structs initialized as C++

I have a struct that looks like this ...

struct Node {
     std::string key, value;
     Node* link;
};

If I initialized an array of nodes as such ...

Node* linkedlist = new Node[100]

How would I iterate over to count how many structs currently exist? I'm implementing a hashmap currently and I need to count how many active buckets there are.

What are structs initialized as C++

When you use

Node* linkedlist = new Node[100];

all the elements of the array are default initialized. key and value are default initialized by calling the default constructor of std::string . link is default initialized, ie left uninitialized.

How would I iterate over to count how many structs currently exist?

You cannot do that given a pointer. That's why std::vector is preferred over dynamically allocated raw arrays. You get a lot more functionality with std::vector .

Instead of

Node* linkedlist = new Node[100];

use

std::vector<Node> linkedlist(100);

Update, in response to OP's comment

When you are not allowed to use std::vector , you'll have to keep track of the number of items in the array yourself.

int numItems = 100; // It could be obtained from the user input also.
Node* linkedlist = new Node[numItems];

Now you can rely on the value of numItems to iterate over the array of Node s in rest of your code.

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