Insert in 2D vector of classes

Dears,

Im using Class called Transaction and I need to create/initializa 2D vector from this class and Insert into it the objects. Kindly advice


// inserting into a vector
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Transaction
{

public:
int pr;
string data;
Transaction::Transaction ();
void assign (string,int);
void print ();
};

Transaction::Transaction (){}

void Transaction::assign (string a,int b)
{
data= a;
pr =b;

}

void Transaction::print ()
{
cout << data;
cout << pr;
}

int main ()
{

Transaction Transobj;
Transobj.data= "Ahmed";
Transobj.pr=1;
vector <vector<Transaction>> Trans1;
Trans1.at(1).push_back(Transobj);

getchar();
return 0;
}
We provided you with code tags... why didn't you use them? T_T

On the line where you have Trans1.at(1)... you are accessing the second element of the vector even though it hasn't been initialized yet. Vectors do have fill constructors that let you declare the starting size of the vector when it's constructed, and I think you might find one of them useful...

http://www.cplusplus.com/reference/vector/vector/vector/

-Albatross
Dear Albatross,

This is the 1st post for me. I believe you mean another one

I checked the link you sent before sending this post but The code fires an error

This is the statement I used for initializing

vector <vector<Transaction>> Trans1 (2,vector<Transaction> (2,0));

I got the below error

1>------ Build started: Project: Project3, Configuration: Debug Win32 ------
'std::vector<_Ty>::vector' : none of the 9 overloads could convert all the argument types
1>          with
1>          [
1>              _Ty=Transaction
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\vector(699): could be 'std::vector<_Ty>::vector(unsigned int,const Transaction &)'
1>          with
1>          [
1>              _Ty=Transaction
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\vector(731): or       'std::vector<_Ty>::vector(const std::vector<_Ty> &,const std::allocator<_Ty> &)'
1>          with
1>          [
1>              _Ty=Transaction
1>          ]
1>          c:\program files (x86)\microsoft visual studio 11.0\vc\include\vector(792): or       'std::vector<_Ty>::vector(std::vector<_Ty> &&,const std::allocator<_Ty> &)'
1>          with
1>          [
1>              _Ty=Transaction
1>          ]
1>          while trying to match the argument list '(int, int)'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========




Also I tried to use the below code

1
2
3
  vector <vector<Transaction>> Trans;

  vector <vector<Transaction>> Trans1 (Trans); 


But I dont know is this 2D vector or 4D vector
Topic archived. No new replies allowed.