I’m having some trouble with vector class. For some reason, yet to be found :P, I can’t insert any objects to my vector. I’ve tried vector, map, deque, etc, but they all have the same weird result.
The object that I want stored is a class with 2 std::string in it. Here’s some code to explain my point:
vector<DnsAddress> * dnss = new vector<DnsAddress>;
for(int i = 0; i < ns.size(); i++){
DnsAddress dn;
dn.SetRecord1(record1);
dn.SetRecord2(record2);
cout<<dn.GetRecord1()<<" : "<<dn.GetRecord2()<<endl; //this works, so it is inserting info to the object
dnss->push_back(dn);//this is where it begins to fail...
cout<<dnss->at(i).GetRecord1()<<" : "<<dnss->at(i).GetRecord2()<<endl;//doesn't work
DnsAddress a = dnss->at(0);//this way doesn't work either...
cout<<"dns: "<<a.GetRecord1()<<endl;
}
I’m sure there must be a rookie mistake.. I hate when those happen.. They consume me some time to find out.
Can someone give a hand with this?
I appreciate it 🙂
To claify:
There are no errors… It works without problem… but the info in the vector gets counted(.size() function tells me the number of inserted objects) but when you try to access it, nothing is shown… But no error is raised
This is class DnsAdress:
class DnsAddress {
public:
DnsAddress();
DnsAddress(const DnsAddress& orig);
virtual ~DnsAddress();
void SetRecord2(string record2);
string GetRecord2() const;
void SetRecord1(string record1);
string GetRecord1() const;
private:
string record1;
string record2;
};
I’ll bet your DnsAddress class needs a copy constructor. This effectively gets invoked when you call push_back on a vector of non-pointer elements.
Edit: Looks like you do have a copy constructor. Actually if you just deleted the copy constructor, the default one would work fine. If you still want to implement it manually, you’ll need to assign record1 and record2 to to orig.record1 and orig.record2 in your copy constructor implementation.