Reputation: 369
For understanding more difficult processes and operations with vectors, I've decided to make a very simple example. So, I have vector, it has structure type. Structure, in its turn, has 3 array: a
, b
, c
. I fill them, and then try to print elements of first array in the structure. But I do something wrong and don't know what exactly, maybe everything. Here is the code:
using namespace std;
struct hl {
int a [3];
int b [3];
int c [3];
};
int main()
{
vector<hl> vec;
struct hl he;
for (int i = 0; i!=3; ++i) {
int aa = 12;
int bb = 13;
int cc = 14;
he.a[i]= aa+i;
cout <<"Hello.a["<< i << "]= "<<he.a[i]<<endl;
he.b[i]= bb+i;
he.c[i]= cc+i;
}
for (std::vector<hl>::iterator it = vec.begin() ; it != vec.end(); ++it) {
//print arr.a[n]
}
return 0;
}
Upvotes: 0
Views: 97
Reputation: 310950
After the loop that fills the arrays of the structure add the following statement
vec.push_back( he );
and then you can output elements of the first array of the structure that is contained in the vector
for ( int x : vec[0].a ) std::cout << x << ' ';
std::cout << std::endl;
Or you could write
for ( const hl &he : vec )
{
for ( int x : he.a ) std::cout << x << ' ';
std::cout << std::endl;
}
Or you could explicitly use iterators of the vector
for ( std::vector<h1>::iterator it = vec.begin(); it != vec.end(); ++it )
{
for ( size_t i = 0; i < sizeof( it->a ) / sizeof( *it->a ); i++ )
{
std::cout << it->a[i] << ' ';
}
std::cout << std::endl;
}
Instead of statement
for ( std::vector<h1>::iterator it = vec.begin(); it != vec.end(); ++it )
you couls also write
for ( auto it = vec.begin(); it != vec.end(); ++it )
Upvotes: 2
Reputation: 11542
You are not adding the element he
to the vector.
You need to do
vec.push_back(he);
The iteration should look like that:
for(std::vector<hl>::iterator it = vec.begin(); it != vec.end(); ++it) {
std::cout << it->a[0] << ", " << it->a[1] << ", " << it->a[2] << std::endl;
}
Also, in C++ you don't need to prepend struct/class variable declaration with struct
keyword. It's C style.
You just need:
hl he;
Upvotes: 1