You are here:

C++/vector as a data member

Advertisement


Question
This is a very short test program where I want to create objects which contain a vector as a data member. I can then add data to that vector from outside. Many of these objects would be created and I could then perform calculations using member functions. I am stuck right at the beginning. I am declaring a vector of double as a data member and tries to add to it but I am getting loads of error since the class does not recognize the vector as a member in the first place. here is my code.


//  Test to verify the use of a vector as a data member
  

#include <iostream>
#include <vector>

using namespace std;


int g;

class Vecttest            // Class definition
{
Public:
  std::vector<double> m_Price;   // Data member
};

int main()
{
  Vecttest aaa;

  // add random values to the vector
  aaa.m_Price.push_back(1.0);
  aaa.m_Price.push_back(2.0);
  aaa.m_Price.push_back(41.0);
  aaa.m_Price.push_back(54.0);

  // Print back the vector data points
  cout << "Stock data: ";
  for(int i=0; i<4; i++)
  {
     cout << aaa.m_Price[i] << ", ";
  }
  
  cin >> g;

  return 0;
}


Thanks for your help.

Answer
Hello Eric.

The problem is that you are using Public with a capital 'P'. It should be lower case.

Also, in your output loop,
for(int i=0; i <4; i++)
it is better to have
for (size_t i = 0; i < aaa.m_Price.size(); i++)

Keep experimenting.
Best regards
Zlatko

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.