1
votes

Bear with me please, this is my first time posting. I have 3 classes. Class Suppliers has a set of Class Parent. Class Parent has a vector of Class location and Class location has data memebers. Ex (this is pseudo code, not my actual code. I've only shown this for simplicity sake):

Class Suppliers{
set<Parent> setter;
};
Class Parent{
vector<location> loc;
};

`

The following is the a constructor of the location class I created. I run into no problems until lines I hit the two lines with the iterators. I am trying to find a specific Parent and push back a new location onto the Parent 'loc' vector. So I pass in the iterator I've found previously as a reference. But as soon as I try to push back the new instance of my location class I get the following error.

data.cpp:139:33: error: passing 'const std::vector' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = location; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::value_type = location]' discards qualifiers [-fpermissive]

The last line also gives an error that says I cannot alter a read-only object. I'm confused as to why this would be a read only object. I did some research and thought that I needed to add a copy constructor. However, that caused more problems than it solved. Any ideas?

location::location(set<Parent>::iterator &it, vector<string> v){ 


 sup_id = v[0];
 address1 = v[2];
 address2 = v[3];
 city = v[4];
 state = v[5];
 country = v[6];
 zip = v[7];
 ((*it).loc).push_back(*this);
 ((*it).num)++;



}
1
Beside @Daniel Frey's answer, you have really poor code design because you should not pass a pointer of your instance during its own construction.Alexandre Severino
@Alexandre Severino, would you suggest when I initialize the object and create a pointer to the object and push it back that way (outside of the constructor)?Katie
Have you considered using a factory pattern? You can create a static method that calls the private constructor for it's own class and, when it is properly instantiated, add to a list. All within this static method. More information on: codeproject.com/Articles/363338/Factory-Pattern-in-CplusplusAlexandre Severino

1 Answers

2
votes

The problem is that a set is sorted. If you'd be allowed to change an element through the iterator, it would basically mean that you could potentially invalidate the iterator and therefore since C++11, the iterator of a set is a constant bidirectional iterator and thereby has the same semantics as the set's const_iterator.

The solution, although slightly ugly, is to remove, modify and re-insert the element. There is a proposal to allow modification of the keys of associative containers, but I don't know if there is any progress in getting it standardized.