How to use vector <struct> of other class

94 views Asked by At
//TreeBox.h
#pragma once
#include "ListBox.h"
struct ItemInfo
{
    std::string _fileName;
    std::string _childName;
    std::string _time;
    std::string _format;
    std::string _size;

    std::string _nodeKey;
};
class TreeBox
{
 ...
}
//ListBox.h
class
{
 public:
 std::vector<ItemInfo> _itemList; //compile error
 
}

I wanna use std::vector in "ListBox.h" from using struct in "TreeBox.h" but it was compile error allocator C2903

how do I use that?

3

There are 3 answers

1
Jon Koelzer On

Simply add #include <vector> to the top of your header to include the STL vector. #including a file header at the top of a file allows you to access the objects defined in that header.

3
Jerry Coffin On

You're including ListBox.h at the beginning of TreeBox.h. Specifically, you're including it before the part of TreeBox.h that defines ItemInfo.

So, you're trying to define a vector<ItemInfo> before the compiler knows what an ItemInfo might be, and it doesn't like that.

Rearrange your definitions so by the time the compiler sees the code trying to create a vector<ItemInfo>, it has already seen the definition of ItemInfo (and be sure you've included <vector>, in case you don't have that yet).

So with things in the correct order, you'd have something like this:

#include <vector> // First, tell the compiler about `vector`

class ItemInfo {  // ...and `ItemInfo`
    // ...
};

class ListBox {
    std::vector<ItemInfo> itemList;  // *Then* we can use `vector` and `ItemInfo`
    // ...
};

If you want some of the pieces of that to be in separate headers that you #include, that's fine--but you still need to get the definitions in the right order.

0
User On
  1. You need not to include ListBox.h in TreeBox.h
  2. Always follow practice of including standard libraries first and then the .h files

#pragma once
#include <vector>
#include <string>
class ListBox;
struct ItemInfo
{
    std::string _fileName;
    std::string _childName;
    std::string _time;
    std::string _format;
    std::string _size;

    std::string _nodeKey;
};
class TreeBox
{

};


#pragma once
#include <initializer_list>
#include "TreeBox.h"

class ListBox
{
public:

    std::vector <ItemInfo> _itemList;
private:

};