Vector and Struct

Hi everyone, I need a good tutorial about the use and management the library vector within the struct. I need to specifically define a vector "m1" as a member of a structure, then, I define a vector "sub" within my main function as a object of this struct, and define too a integer "lista". The compile it's good, but I need assign some value to m1[i][j], i.e., storage in both indices of the vector "m1". In the following example no compilation errors, however every component "i" of the vector "m1" are equal.

--------------------------------------------------------------------------
#include<iostream>
using namespace std;
--------------------------------------------------------------------------
struct subject {
vector<int> m1;
};
--------------------------------------------------------------------------
int main() {
int i=0, j=0;
int nn=5;
int nb[nn];

vector<subject> sub;

subject lista;

for(i=0;i<nn;i++)
nb[i] = i*i;

for(i=0;i<nn;i++)
lista.m1.push_back(nb[i]);

for(i=0;i<nn;i++)
sub.push_back(lista);

for(i=0;i<nn;i++)
for(j=0;j<nn;j++)
cout<<"sub("<<i<<").m1("<<j<<") = "<<sub.at(i).m1.at(j)<<"\n";
}
--------------------------------------------------------------------------

How your see, I need write in both component of vector "m1".

Appreciate any help. Thank.
Don't do this. The size of an array should be a compile time constant.
1
2
nt nn=5;
int nb[nn];
There is some confusion over this feature. It's a C99 feature that GCC allows in C++, but it's not valid C++.

I need a good tutorial about the use and management the library vector within the struct
There isn't a seperate tutorial on these things. The rules on members of a struct a pretty clear, and so is the behaviour of std::vector.

Instead of this:
1
2
for(i=0;i<nn;i++)
    lista.m1.push_back(nb[i]);
you can do this:
 
lista.m1 = nb;


And instead of this:
1
2
for(i=0;i<nn;i++)
    sub.push_back(lista);
you can do this:
 
vector<subject> sub(nn, lista);
http://www.cplusplus.com/reference/stl/vector/vector/

With the help of some convenient constructors:
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
#include <iostream>
#include <vector>

using namespace std;

struct subject
{
        subject() {}
        subject(int* array, size_t sz) : m1(array, array + sz) {}

        vector<int> m1;
};

int main()
{
        const int nn=5;
        int nb[nn];
        for (int i = 0; i < nn; ++i)
                nb[i] = i*i;

        subject lista(nb, nn);
        vector<subject> sub(nn, lista);

        for (int i = 0; i < nn; ++i)
        {
                for (int j = 0; j < nn; ++j)
                        cout << "sub(" << i << ").m1(" << j << ") = " << sub.at(i).m1.at(j) << " ";
                cout << std::endl;
        }

        return 0;
}
Last edited on
Topic archived. No new replies allowed.