Another struct question

This my .h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
 private:
 struct test
    {
        Key obj;
	vector<Value> contain;

        test( const Key & e = Key( ), const Value & a = Value())
	{
		obj= e;
		contain.push_back(a);
	}
          
    };
    vector<test> array;


I am unclear of how to print or access the data in contain. I know for obj I would have to use
1
2
for(int i = 0; i < array.size(); i++)
cout << array[i].obj;

could someone help me out?
Thank You
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 private:
 struct test
    {
        Key obj;
	vector<Value> contain;

        test( const Key & e = Key( ), const Value & a = Value())
	{
		obj= e;
		contain.push_back(a);
	}
          
    };
    vector<test> array;


In the code you showed array has no elements. Let assume that you added some elements to array.

for ( int i = 0; i < 10; i++ ) array.push_back( test() );

Then you can output contain of each element in array.

1
2
3
4
5
6
7
8
for ( std::vector<test>::size_type i = 0; i < array.size(); i++ )
{
   for ( std::vector<Value>::size_type j = 0; j < array[i].contain.size(); j++ )
   {
      std::cout << array[i].contain[j] << std::endl;
   }
   std::cout << std::endl;
}


Statement std::cout << array[i].contain[j] << std::endl; will be correct if there is overload operator << for type Value.

Also take into account that statement

vector<test> array;

shall be removed from the header and placed in a module.

I have not learned std::vector<test>::size_type i = 0; so I can't use it in the assignment. I tried int i = 0; but got alot of errors?
You may change
std::vector<test>::size_type i = 0;
to
unsigned int i = 0;
I took out the scope resolution operator because I include namespace but the following still produce error.

1
2
3
4
5
6
7
8
9
for ( vector<test>::unsigned int i  = 0; i < array.size(); i++ )
{
	  for ( vector<Value>::unsigned int j  = 0; j < array[i].contain.size(); j++ )
	  {
		 cout << array[i].contain[j] << endl;
	  }
		   cout<< endl;
}


Last edited on
Show error messages.
I am sorry. You shall write


1
2
3
4
5
6
7
8
for ( unsigned int i  = 0; i < array.size(); i++ )
{
	  for ( unsigned int j  = 0; j < array[i].contain.size(); j++ )
	  {
		 cout << array[i].contain[j] << endl;
	  }
		   cout<< endl;
}
Last edited on
Okay that works. Thanks for being so helpful and patience, I really appreciate it
Topic archived. No new replies allowed.