This may be a simple fix, but I have a class for a program that contains some member functions that manipulate a vector. The vector is a private member variable, and is filled from an array using a constructor. When I try to access the member functions to manipulate the vector, the vector is empty. I have tested the constructor and member functions separately and they work fine on their own. Here is the code:

class and #include directives

#include <iostream>
#include <vector>
using namespace std;

class NumberSet
{
      public:
             void add (int A); //adds an element to the set if not already present
             NumberSet(int array1[], int size); //transfers the data from an array to a vector
             NumberSet( ); //default constructor
             int array_size_horizontal;
      private:
              vector<int> v1;
              int vectorsize;
};

Constructor

NumberSet::NumberSet(int array1[], int size)
{
    for (int e=0; e < size; e++) 
        v1.push_back(array1[e]);
}

Member Function Declaration

void NumberSet::add(int A){
//need it to test for each element's value and when it gets to the end, if none are equal, then use push_back

	 if(v1.size() == 0)
		 v1.push_back(A);
	 else{
		 bool found = false;
		 unsigned int index = 0;

		 while(!found && index < v1.size() )
                 {  
			 if(v1[index] == A)
				 found = true;
			 index++;
		 }

		 if(!found)
			 v1.push_back(A);
	 }
}

Main Function

int main()
{
  
//  int next;
    int horcounter = 0;
    int nextcounter = 0; 
    
    int array1[6];
    NumberSet runonce;
    cout << "Please enter 6 integers, then press return: ";
    for (int j=0; j < 6; j++)
    {
        cin >> array1[j];
    }
	for (int j=0; j < 6; j++)
    {
        cout << array1[j] << endl;
    }
    NumberSet first(array1, 6); //calling the constructor
    
    int input1;
    cout << "To test the add function, please enter an integer and press return: ";
    cin >> input1;
    runonce.add(input1);

    return 0;
}

If anybody knows why I cannot get the function to access the vector, any help would be greatly appreciated.

Never mind, I feel stupid now. The problem was in my calling the constructor. I called it using NumberSet runonce . However, the vector was filled when I called it NumberSet first(array1, 6) . All I had to do was get rid of the runonce and change line 24 to first.add(input1) . Now it works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.