#include <iostream>
#include <vector>
#include <iterator>

using namespace std;

class members
{
 private:
 int Age;
 int Money;

 public:
 void setAge(int age) {Age=age;}
 void setMoney(int money) {Money=money;}
 int getAge()const {return Age;}
 int getMoney()const {return Money;}
 members(int age=0,int money=0): Age(age),Money(money) {}
};

int main()
{
vector<members>v_members;
for(size_t i=0,z=0;i<10;++i,++z)
    {
     if(z!=5) { v_members.push_back(members(50,70)); }
    }
}

I wrote a litte program for a better understanding of a classvector and costructors. It should be ok but there are two questions.

  • How could one insert new elements in the vector ?
  • Would it be a good idea to create the vector within the class / the constructor?
    If so, how could this be done and how could data then be saved in the main?

Recommended Answers

All 7 Replies

How could one insert new elements in the vector ?

By using std::vector::push_back or std::vector::insert function

Would it be a good idea to create the vector within the class / the constructor?

Sure, if you need an array of something, then std::vector is usually a good choice.

For how it could be done see:

class Members
{
    private:
        vector<int> Data;

    public:
        Members(){}
        Members(int I);
        ~Members(){}


        int size();
        Members& operator [](int I);
        operator const vector<int>& () const;
        Members& operator ()(int I);
        Members& operator << (const int& t);
        Members& Insert(int Index, int ValueToInsert);
        Members& Remove(int Index);
};

int Members::size(){return Data.size();}   //Just return the size of the vector.

Members& Members::operator [](int)  //Don't forget to overload the const version of this.
{
    assert(I >= 0 && !Data.empty());        //Make sure the indicies accessed are correct.
    return Data[I];                     //return the value at that position in the vector.
}

Members::operator const vector<int>& () const
{
    return Data;
}

Members& Members::operator ()(int I)
{
    Data.push_back(I);      //Same thing as below.. Insert every int into the vector.
    return *this;
}

Members& Members::operator << (const int& I)    //Overloads the insertion operator.
{
    Data.push_back(I);      //Every int inserted gets pushed back to the vector.
    return *this;
}

Members& Members::Insert(int Index, int ValueToInsert)
{
    //Code to insert at a position in the vector. ;) I'll leave this up to you. It's about 1 line
    return *this;
}

Members& Members::Remove(int Index)
{
    //Code to remove a value at that position in the vector. I'll also leave this up to you.
    return *this;
}


//Finally you use it like:

Member X(1);
X(2);
X(3);
X<<4<<5<<6<<7;
X<<8;

for (int I = 0; I < X.size(); I++)
    cout<<X[I]<<endl;

Now you can learn to overload the rest of the operators to check for equality, ostream for printing them, etc.. but this class is a bit complexed and will get complexed depending on the usage and what data it holds. Basically all of that can be done exactly how you've done it already. You can always just stick to adding the classes to the vector like you've already done. OR you can do the above and add the vector to the class, essentially making the class a dynamic array.

using std::vector::push_back or std::vector::insert function

vector<member>::iterator it;
it = v_member.begin()+3;
it = v_member.insert ( it , 200 );

Yes, but it works not really because there is only one element inserted, but in the class are two elements.
So how can I use the insert function for inserting age and money in the vector?

Now you can learn to overload the rest of the operators to check for equality but this class is a bit complexed and will get complexed depending on the usage and what data it holds. You can always just stick to adding the classes to the vector like you've already done. OR you can do the above and add the vector to the class, essentially making the class a dynamic array.

Thanks a lot for this code. Its great stuff :-) I need time to understand the code.
I tried to compile it, unfortunately the compiler (I use Codeblocks, GCC) doesn't compile it.

Error Messages:
main.cpp||In member function 'Members& Members::operator':|
main.cpp|26|error: 'I' was not declared in this scope|
main.cpp|26|error: 'assert' was not declared in this scope|
main.cpp|54|error: 'Member' does not name a type|
main.cpp|55|error: expected constructor, destructor, or type conversion before '(' token|
main.cpp|56|error: expected constructor, destructor, or type conversion before '(' token|
main.cpp|57|error: expected constructor, destructor, or type conversion before '<<' token|
main.cpp|58|error: expected constructor, destructor, or type conversion before '<<' token|
main.cpp|59|error: expected unqualified-id before 'for'|
main.cpp|59|error: expected constructor, destructor, or type conversion before '<' token|
main.cpp|59|error: expected constructor, destructor, or type conversion before '++' token|

Here try this.. I missed a bracket above and a couple other details as I wrote that on the spot without a compiler.. Also I didn't notice that you had both Age AND Money for your constructor. Thus instead we change all the int's to a pair or a map and add the ostream operator. In codeblocks this looks much easier on the eyes! Looks way harder on this forum due to the extra large font..

#include <windows.h>
#include <iostream>
#include <vector>
#include <assert.h>
#include <map>

using namespace std;

class Members
{
    private:
        vector< pair<int, int> > Data;

    public:
        Members(int age = 0, int money = 0);
        ~Members(){}


        int size();
        pair<int, int>& operator [](int I);
        const pair<int, int>& operator [](int I) const;
        operator const vector< pair<int, int> >& () const;
        Members& operator ()(int age = 0, int money = 0);
        Members& operator << (const pair<int, int>& t);
        friend ostream& operator << (ostream& Str, const Members& Pairs);
        Members& Insert(int Index, pair<int, int> ValueToInsert);
        Members& Remove(int Index);
};

Members::Members(int age, int money)
{
    Data.push_back(make_pair(age, money));
}

int Members::size(){return Data.size();}   //Just return the size of the vector.

pair<int, int>& Members::operator [](int I)
{
    assert(I >= 0 && !Data.empty());        //Make sure the indicies accessed are correct.
    return Data[I];                     //return the value at that position in the vector.
}

const pair<int, int>& Members::operator [](int I) const
{
    assert(I >= 0 && !Data.empty());        //Make sure the indicies accessed are correct.
    return Data[I];                     //return the value at that position in the vector.
}

Members::operator const vector< pair<int, int> >& () const
{
    return Data;
}

Members& Members::operator ()(int age, int money)
{
    Data.push_back(make_pair(age, money));      //Same thing as below.. Insert every pair into the vector.
    return *this;
}

Members& Members::operator << (const pair<int, int>& I)    //Overloads the insertion operator.
{
    Data.push_back(I);      //Every pair inserted gets pushed back to the vector.
    return *this;
}

ostream& operator << (ostream& Str, const Members& Pairs)     //This is the ostream operator overload which lets them print however you want!
{
    if (!Pairs.Data.empty())  //check to see if it's empty. If it is, forget it.
    {
        Str<<"[";
        for (unsigned I = 0; I < Pairs.Data.size() - 1; I++)   //Iterator our vector.
        {
            Str<<"nAge: "<<Pairs.Data[I].first<< " Money: $"<<Pairs.Data[I].second<<" n ";  //Insert all the data into the ostream.
        }
        Str<<"nAge: "<<Pairs.Data[Pairs.Data.size() - 1].first<< " Money: $"<<Pairs.Data[Pairs.Data.size() - 1].second<<"n]"; //Inser the very last one.. useful if you had commas above and don't want the last value ending with a comma.
    }
    else
        Str<<"[]";  //If our vector was empty, we print just some brackets.

    return Str;
}

Members& Members::Insert(int Index, pair<int, int> ValueToInsert)
{
    //Code to insert at a position in the vector. ;) I'll leave this up to you. It's about 1 line
    return *this;
}

Members& Members::Remove(int Index)
{
    //Code to remove a value at that position in the vector. I'll also leave this up to you.
    return *this;
}

int main()
{
    Members X(21, 50000);    //As we defined in our constructor, Age is the first value, Mone yis the second..
    X(22, 100);    //Age, Money.
    X(30, 13134);   //Age, Money.

    X<<make_pair(50, 200000)<<make_pair(81, 70000);  //We inserted a pair because our overload for the insert operator takes a pair as it's parameter. You can easily overload it again to take members as well or any other things you want. It's all up to you!
    X<<make_pair(90, 42342515);

    cout<<X<<endl;  //This is the magical ostream operator. It prints them exactly how we defined in the class.
}

THIS IS VERY COMPLEXED if your just starting out. Of course pro's are going to understand it but if you don't. Definitely leave a comment and I will help you out for sure if I see it. Also you need to study the class above to fully understand it if you don't. It will be very helpful to understand what's going on there.

Now after all that's said and done, I'd like to see you do the insert and remove operators. It'll be pretty easy you can trust me on that. Oh and all of this could easily have been done with exactly what you did before. Basically this class has an underlying vector that holds all the data for it. If you didn't want that, you could do it how you had it before by just doing:

Member Meh(age, money);
vector.push_back(Meh);      //Basically the same thing as all of the above.

Yes, now it works.
Thank you very much, now I have a lot to study.
Indeed it is very complex as I am a beginner, a rudimentally understanding is given,but not more.
I will write the insert und remove operators, let me take a look at the code, please

For inserting into the vector the code should be:

Data[Index]=ValueToInsert;

and for removing an element it should be:

Data.erase (Data.begin()+(Index-1));

Could you please add this to your code, so other users have a complete program?

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.