deleting vector elements using pointers

Discuss all kind of algorithms and data structures from their mathematical and programming sides.

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

deleting vector elements using pointers

Postby dipperdan » Sat Feb 19, 2005 1:20 pm

Hi guys,
I was wondering if there is a way to delete elements of a vector using pointers. In my tutorial class for an Information Structures course, in answer to the highlited part of the following question:

1.Develop a C++ function with a vector called Numbers to store integers. Resize Numbers to hold 10 integers. Insert the integers 1 to 10 into Numbers. Print the integers in forward and reverse order. Delete the first, last and fifth elements and print Numbers again.

gave us this answer:
Code: Select all
.
.
int *n1, *n2, *n3;

n1 = &Numbers[0];
n2 = &Numbers[9];
n3 = &Numbers[4];

delete n1;
delete n2;
delete n3;
.
.


This looked a little fishy to me so i compiled it in DevC++ and when i printed the vecotor the values of those elements were garbage values (definitely not in the range 1-10). So i did some research online and found out about iterators and this seems like a good way to go about it, but i was wondering if someway somehow this pointers thing could still work?
User avatar
dipperdan
 
Posts: 142
Joined: Sat Apr 24, 2004 10:40 am
Location: Barbados, West Indies

Postby MXP » Sat Feb 19, 2005 1:24 pm

Deleting pointers will not remove the elements from the vector. If you are to delete elements then you want to use the vector's erase() method.
Need information on a function I've posted? Chances are it's at the MSDN.
MXP
 
Posts: 6506
Joined: Mon Sep 22, 2003 5:27 pm

Postby dipperdan » Sat Feb 19, 2005 1:27 pm

Thanks for that clarification
User avatar
dipperdan
 
Posts: 142
Joined: Sat Apr 24, 2004 10:40 am
Location: Barbados, West Indies


Return to Algorithms & Data Structures

Who is online

Users browsing this forum: No registered users and 0 guests