# How to use vector of structure ?

• 09-18-2005
franziss
How to use vector of structure ?
Code:

```struct structtid {   int tid; //transaction id list   int *tidptr;  // pointer to the transaction   int transnum; //size of each transaction }; <vector>structtid t; structtid temp; temp.tid = 1; temp.transnum = 10; t.push_back(temp);```
I tried to add a structure into t but there is error. I also try to declare <vector>int tidptr in sttucttid, but there is error too..

Can anyone help me? Thanks!
• 09-18-2005
laserlight
Um, maybe because the syntax is vector<structtid> and vector<int>?
• 09-18-2005
Epo
Using:

#include <vector>

Will allow you to declare a vector from the Standard Template Library:

std::vector<int> Ages(10);

Writing std:: all the time though could be a little annoying. So after the include, writing:

using namespace std;

Will import the std namespace and now you can just:

vector<int> Ages(10);

To declare 10 spots for an integer in the vector called Ages.
• 09-18-2005
franziss
I understand that a vector of integer can be declared and elements in integer can be easily added to it. But what about a vector of structure? Where the structure is defined by me. Can it be done too?
• 09-18-2005
Tonto
I see absolutely no reason why you could not ;) I also added onto your code. A nifty feature of C++ is the fact the structs and classes are exactly the same (public vs. private, whatev). This means you can have a struct constructor, reducing the need for your temporary struct to push onto the vector. This code works fine for me.

Code:

```struct structtid {         int tid;      // transaction id list         int *tidptr;  // pointer to the transaction         int transnum;  // size of each transaction         structtid(int tid, int transnum)         {                 this->tid      = tid;                 this->transnum = transnum;         } }; int main(int argc, char *argv[]) {         std::vector<structtid> t;         t.push_back(structtid(1, 10));         return 0; }```
I see absolutely no reason why you could not ;)
• 09-18-2005
franziss
whoa! thanks, i think this is what i need. i will try it later. thanks!