Vectors of objects in a class

I have a class Table which contain a vector of Fields. This little program will not quite compile. Issues on the lines 24 and 45. I am trying to understand how I can print the names of the Fields in the Table.

There probably is a better way to do this, but I would like to make this works from this principle.

Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <cstdlib>
#include <iostream>
#include <pqxx/pqxx>
#include <vector>

class Fields{
    public:
        std::string name;
        std::string type;
        int max_size;
        void printFieldNames();
};

class Table{
    public:
        std::string name;
        std::vector<Fields> table_fields;
        void readFields();
        void displayFields();
};

void Table::displayFields(){
    for(size_t i=0; i<table_fields.size(); ++i){
        std::cout<<"Field" << table_fields[i].name <<std::endl;//This not printing right
    }
}

void Table::readFields(){
    using namespace std;
    pqxx::connection c("dbname=mydb user=postgres");
    pqxx::work txn(c);

    pqxx::result r = txn.exec("SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name='employee'");
    for (pqxx::result::const_iterator row = r.begin(); row != r.end(); ++row)
    {
        vector<string>v;
        for (pqxx::result::tuple::const_iterator field = row->begin(); field != row->end(); ++field){
            v.push_back(field->c_str());
        }
        Fields f;
        table_fields.push_back(f);
        f.name=v[0];
        cout<<"name :"<<v[0]<<endl;
        cout<<"f.name :"<<f.name<<endl;
        cout<<"table_field....f.name :"<<table_fields[0].name<<endl;  //Confused....
        f.type=v[1];
        f.max_size=atoi(v[2].c_str());
    }  
}

int main(int, char *argv[])
{
    Table T;
    T.readFields();
    T.displayFields();
    return 0;
}

//g++ -std=gnu++11 -g -o listpeople listpeople.cpp -I/usr/lib -lpqxx -lpq 
Line 41 is inserting a copy of the Field into the vector, it isn't f.

You need:
1
2
3
4
5
6
7
8
9
10
Fields f;
f.name = v[0];
// initiate the rest of f's variables
table_fields.push_back(f);

// or

table_fields.push_back(Fields());
table_fields.back().name = v[0];
//initiate the rest of back's variables 

Last edited on
Thanks LowestOne.
I implemented your second option. works perfectly.
1
2
3
4
table_fields.push_back(Fields());
table_fields.back().name=v[0];
table_fields.back().type=v[1];
table_fields.back().field_size=atoi(v[2].c_str());
Topic archived. No new replies allowed.