|
-
May 3rd, 2002, 07:58 PM
#1
Thread Starter
Frenzied Member
delete a vector element and have all the rest shift up?
say I have an vector with
2
5
8
2
and I deleted 5 (first off, how would I delete 5?). How can I then have 8 and 2 shift up so the new vector is
2
8
2
retired member. Thanks for everything 
-
May 3rd, 2002, 08:44 PM
#2
You would probably write a vector wrapper:
Code:
template<class t>
class shift_vector
{
private:
std::vector<t> m_vector;
public:
shift_vector();
~shift_vector();
void RemoveElement(unsigned int index);
...
};
You would then code the RemoveElement to iterate through the m_vector member, starting at the index to remove. The one above it would shift down one, and overwrite the index to remove. Continue this process until you hit m_vector.size()-1. Then, resize().
Z.
-
May 3rd, 2002, 08:50 PM
#3
Thread Starter
Frenzied Member
yeah...I was wondering if there is a prewritten function for this. Guess not.....
retired member. Thanks for everything 
-
May 4th, 2002, 04:02 PM
#4
I posted the algorithm. You should be able to implement it yourself.
Z.
-
May 4th, 2002, 05:03 PM
#5
Monday Morning Lunatic
If you're using the STL, then you can swap vector for deque, and use the pop_front method
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
May 4th, 2002, 05:26 PM
#6
Thread Starter
Frenzied Member
yeah...
I couldnt find vector.h anywhere so I found it on some school website. It only has 2 functions. Did I get some base version of it?
retired member. Thanks for everything 
-
May 4th, 2002, 05:27 PM
#7
Monday Morning Lunatic
It's just <vector>, not <vector.h>. The standard c++ library headers have no .h extension.
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
-
May 5th, 2002, 10:48 AM
#8
Or you use a double linked list (<list>). The architecture of a list makes the shifting unnecessary.
That depends on what you want to do with the whole thing though...
BTW, calling vector::erase will automatically shift the elements after the deletion point, but all references to elements after the deletion point become invalid:
Code:
vector<int> vi;
// add 10 elements with the value 5
vi.insert(vi.end(), 10, 5);
// get a reference to the 6th element
int &ri = vi[5];
// delete the second element
vector<int>::iterator it = vi.begin();
it++;
vi.erase(it);
// INVALID!!! May produce unforeseeable results!
dosomething(ri);
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|