extracting object from std::vector<classA>

I have defined a std::vector<classA> classAVector to hold instance of classA.

Now I like to do a for loop with the following.

classA  instance;
int size = classAVector.size();
int i=0;

while (i<size)
{
       instanceA = classAVector [i];
       cout << instanceA.Name << endl;
       i++; 
}

Open in new window

I seems to be able to get the first element out properly, but i have problem getting the 2nd or the rest all wrong. Why? Or how do I fix it without using iterator.
tommym121Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jkrCommented:
Judging from only the above snippet, it should work (even though you should consider using 'classA& instance;' instead to avoid the overhead of copying an object). With an iterator, that would be like

for (vector<classA>::iterator i = classAVector.begin(); i != classAVector.end(); ++i) [

  cout << i->Name << endl;
}

Open in new window

0
phoffricCommented:
I didn't see anything wrong with what you posted (other than your style - usually we use iterators to iterate through a vector). I suspect that you have not set up your vector correctly. Here is a small program that uses your code, but shows how to add items to your vector:
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class classA {
public:
   //classA() {}
   //classA(string str) : Name(str) {}
   string Name;
};

std::vector<classA> classAVector;
classA  instanceA;

int main() {
   instanceA.Name = "First";
   classAVector.push_back(instanceA);
   instanceA.Name = "2nd";
   classAVector.push_back(instanceA);
   instanceA.Name = "3rd";
   classAVector.push_back(instanceA);
   int size = classAVector.size();
   int i=0;

   while (i<size)
   {
      instanceA = classAVector [i];
      cout << instanceA.Name << endl;
      i++; 
   }
}

Open in new window

0
phoffricCommented:
Thought about your problem a little more. Using the above way to setup a vector, I didn't see how you only got the first vector element. Maybe you used the following approach, but forgot to increment the index:
   std::vector<classA> classAVector (3);   // 3 zero-initialized elements

   classAVector[0].Name = "First";
   classAVector[1].Name = "2nd"; // don't forget to increment the index
   classAVector[2].Name = "3rd";

Open in new window

If you only used index of 0, then the remaining strings would be zero-initialized, and the output would be blank lines.
0
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

phoffricCommented:
Off topic since your code snippet in your OP is actually working, if you use VS 2010, then you have C++11 lamda expressions included. Then your output loops can be replaced with:
for_each(classAVector.begin(), classAVector.end(), [](classA ca){cout << ca.Name << endl;} );

Open in new window

You have to also include <algorithm> header. This for_each reference, shows other pre-C++11 ways to get your output without loops.

If using g++, to get their C++11 functionality, add some of these compiler options -std=c++11 or -std=gnu++11 or -std=gnu0x or -std=c++0x.
0
evilrixSenior Software Engineer (Avast)Commented:
If all you want to do is output the name of each item you can just do something like this...

#include <iostream>
#include <iterator>

namespace std {
   std::ostream operator << (std::ostream & out, classA const & a)
   {
      return out << a.Name << std::endl;
   }
}

std::copy(classAVector.begin(), classAVector .end(),
                  std::ostream_iterator<classA>(std::cout));

Open in new window

0
tommym121Author Commented:
I got this error

vector2.cpp(68): error C2440: 'initializing' : cannot convert from 'std::vector<_Ty>' to 'itemENTRY'

This is the line
itemENTRY item =  pItemTable[incr2];  // <===  vector2.cpp(68)

Here is the code.
// Vector2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <vector>
#include <iostream>
typedef struct _ItemENTRY
	{
	wchar_t *Name;
	int val1, val2, val3;
	} itemENTRY;
	
typedef struct _ContainerENTRY
	{
	wchar_t *lpszName;
	wchar_t *lpszID;
	std::vector <itemENTRY> *pItemTable;	
	int nItemTableSize;
	} ContainierENTRY;
using namespace std;	
#define TABLESIZE(x) ((int) (sizeof (x) / sizeof (x [0])))
#define TABLESIZE_1(x) ((int) ((x).size()))

itemENTRY ItemTableContainer1 [ ] = 
	{
	// Name,			val1,	val2,	val3,	
	L"Tag1",			0,			0,			0,			
	L"Tag2",			0,			0,			0,			
	L"Tag3",			0,			0,			0,			
	L"Tag4",			0,			0,			0,			
	L"Tag5",			0,			0,			0,			
	};
	
itemENTRY ItemTableContainer2 [ ] = 
	{
	// Name,			val1,	val2,	val3,	
	L"Item1",			0,			0,			0,			
	L"Item2",			0,			0,			0,			
	L"Item3",			0,			0,			0,			
	};
	
// Below is the original test data, i will try to read it in instead  from <name>_cfg.csv
std::vector<itemENTRY> ItemTableContainer1_Vector (ItemTableContainer1, ItemTableContainer1 + TABLESIZE(ItemTableContainer1));
std::vector<itemENTRY> ItemTableContainer2_Vector (ItemTableContainer2, ItemTableContainer2 + TABLESIZE(ItemTableContainer2));


ContainierENTRY ContainerEntries [ ] =
	{
	// Name,				ID,					ItemsContainer_Vector,				Size
	L"Container1",			L"1",				&ItemTableContainer1_Vector,		TABLESIZE_1 (ItemTableContainer1_Vector),
	L"Container2",			L"2",				&ItemTableContainer2_Vector,		TABLESIZE_1 (ItemTableContainer2_Vector),
	};
	
std::vector<ContainierENTRY> Container (ContainerEntries, ContainerEntries + TABLESIZE(ContainerEntries));	
	

int _tmain(int argc, _TCHAR* argv[])
{
	int incr1=0, incr2;
	while (incr1 < TABLESIZE_1 (Container)) 
	{
			ContainierENTRY containerItem = Container[incr1];
			std::wcout << "Name = " << containerItem.lpszName << "; ID = " << containerItem.lpszID << endl;
			std::vector<itemENTRY> *pItemTable = Container [incr1].pItemTable;
			incr2=0;
			while (incr2 < Container [incr1].nItemTableSize)
			{
				itemENTRY item =  pItemTable[incr2];  // <===  vector2.cpp(68)
				std::wcout << "Item Name = " << item.Name  << endl;
				incr2++;
			}
			incr1++;
	}
	return (0);
}

Open in new window

0
jkrCommented:
Your vector is a pointer here, thus you have to reference it the right way - line 68 should be

itemENTRY item =  (*pItemTable)[incr2]; // '*' means 'use the instance here'

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tommym121Author Commented:
Thanks
0
tommym121Author Commented:
Thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.