@
keskiverto
He made
ref global because
find_pos() needs that information to sort properly. Also, the object is not to make the STL do it. The object is to do it himself. (Hence the instruction to make the 'where to insert' function.)
@
LA101
The point that you are inserting the same data into your vector twice should not be ignored. Don't do that. (Get rid of line 63.)
The reason you are getting an access error is because of the following situation:
ref == (0,0);
vector == { (1,1), (2,2), (3,3) };
p == (5,5);
Where does p go? At the end, of course.
But your loop (line 41) is not terminated with a valid value for
position when it gets to line 57. The return value, then, is garbage, and may be
anything, like -1 or 5000012. These are, of course, invalid values to access your vector, and as a result, throw an invalid access error and terminate your program.
Fix it by changing line 33:
int position = v.size();
-- meaning, should a proper insert position
not be found by the loop (and a value assigned to
position before quitting the loop), then the proper place to "insert" is at the end (since that was the value of
position before the loop began).
The next problem you have is the logic inside the loop to terminate. (It's wrong.) The trick is to go through the elements, one by one, and ask:
is the Manhatten distance to p still less than the Manhatten distance to the current element?. If it is
not, then you have found your insert position. That's it!
Your compiler should be complaining about comparing signed and unsigned values. Use
size_t as your index into a vector.
for (size_t i = 0; i < v.size(); i++)
This isn't big, however, and you need not worry about it. (Particularly as your assignment does specifically say to return an
int for an index.)
Finally, about the global. For your schoolwork, it is fine. But your assignment gives you the ability to gain points for passing it as a reference:
31 32 33
|
int find_pos(vector<point>&v, point p, point ref)
{
...
|
61 62 63 64 65
|
void ord_ins(vector<point>& v, point p, point ref)
{
int position = find_pos(v,p,ref);
v.insert((v.begin()+position),p);
}
|
Hope this helps.