473,704 Members | 2,408 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

delete elements in vector

I want to delete all even numbers in a vector, I am not sure if there's
any better way to do it. Following program is how I did it.
Look at the part of code beginning from
comments: //delete all even numbers.

My questions is actullay I have to put pos++ in the body of the
loop(also in if, else, statement). Can I somehow put it in
for(...;...;... ).

Or can I use index instead of iterator in order to delete elements from
vector?

I just wish to know what's the most elegant way to do it.

Thanks

#include <iostream>
#include <vector>

main(){

int ar[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

vector<int> tmpint;

//populate vector
for(int i=0; i<10; i++){
tmpint.push_bac k(ar[i]);
}

//delete all even numbers
vector<int>::it erator pos;
for(pos=tmpint. begin(); pos != tmpint.end(); ){
if (*pos % 2 == 0)
tmpint.erase(po s);
else
pos++;
}

//display all elements in the vector
for(pos=tmpint. begin(); pos != tmpint.end();po s++ ){
cout<<*pos<<end l;
}
}

Jul 23 '05 #1
9 3609
david wolf wrote:
I want to delete all even numbers in a vector, I am not sure if there's
any better way to do it. Following program is how I did it.
Look at the part of code beginning from
comments: //delete all even numbers.

My questions is actullay I have to put pos++ in the body of the
loop(also in if, else, statement). Can I somehow put it in
for(...;...;... ).

Or can I use index instead of iterator in order to delete elements from
vector?

I just wish to know what's the most elegant way to do it.
Elegance is in the eye of the beholder. You can try doing it in one line
(well, not exactly, you'll need to define your predicate), but whether
it's "elegant" or not is not my place to say.

Thanks

#include <iostream>
#include <vector>

main(){
int main(){

int ar[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

vector<int> tmpint;
std::vector<int > tmpint;

//populate vector
for(int i=0; i<10; i++){
tmpint.push_bac k(ar[i]);
}
Did you know you can initialise 'tmpint' from 'ar' in the same statement
where you declared it?

std::vector<int > tmpint(ar, ar + 10);

?? No need for the loop at all...

//delete all even numbers
vector<int>::it erator pos;
std::vector<int >::iterator pos;
for(pos=tmpint. begin(); pos != tmpint.end(); ){
if (*pos % 2 == 0)
tmpint.erase(po s);
else
pos++;
}

//display all elements in the vector
for(pos=tmpint. begin(); pos != tmpint.end();po s++ ){
cout<<*pos<<end l;
std::cout << *pos << std::endl;
}
}


If you use 'std::remove_if ' and a custom predicate, you can do

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// your custom predicate
template<class T> struct is_even {
bool operator()(T t) const {
return t % 2 == 0;
}
};

int main(){
int ar[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> tmpint(ar, ar+10);

// this is essentially your one-liner.
tmpint.erase(
remove_if(tmpin t.begin(),
tmpint.end(),
is_even<int>()) ,
tmpint.end());

//display all elements in the vector
for (size_t i = 0; i < tmpint.size(); i++)
cout << tmpint[i] << ' ';
cout << endl;
}

V
Jul 23 '05 #2

david wolf wrote:
I want to delete all even numbers in a vector, I am not sure if there's any better way to do it. Following program is how I did it.
Look at the part of code beginning from
comments: //delete all even numbers.

My questions is actullay I have to put pos++ in the body of the
loop(also in if, else, statement). Can I somehow put it in
for(...;...;... ).
You probably could, but I don't think it's worth it.

Or can I use index instead of iterator in order to delete elements from vector?

I just wish to know what's the most elegant way to do it.

Thanks

#include <iostream>
#include <vector>

main(){

int ar[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

vector<int> tmpint;

//populate vector
for(int i=0; i<10; i++){
tmpint.push_bac k(ar[i]);
}

//delete all even numbers
vector<int>::it erator pos;
for(pos=tmpint. begin(); pos != tmpint.end(); ){
if (*pos % 2 == 0)
tmpint.erase(po s);
else
pos++;
}

//display all elements in the vector
for(pos=tmpint. begin(); pos != tmpint.end();po s++ ){
cout<<*pos<<end l;
}
}


I'm not convinced this piece of code even does what it is supposed to
do - AFAIK the iterator pos is not guaranteed to be valid after calling
erase. I think you should use

pos = tmpint.erase(po s);

instead. This will make pos point to the next, non-erased element after
pos, or end() if there aren't any.

As far as elegance goes, the method erase works in linear time on
vectors: to erase an element, it simply moves all elements behind it
left one place (filing up the erased spot). This will create a lot of
unnecessary copying if you call erase lots of time in succession on the
same vector. So this is not very elegant I'm afraid. It is of course
possible to examine/erase/move every element in the vector only once,
if you think about it for a bit. It is possible that the remove_if that
Victor Bazarov suggested is implemented like that (I haven't checked,
but it seems likely) so I second his suggestion that you give that a
try.

grtz Mark

Jul 23 '05 #3
I do not agree with grtz Mark. I tried my program, it works fine. I
means it is not necessary to use
pos = tmpint.erase(po s);

simply doing
tmpint.erase(po s);

will work. Any one giving me some opnions?

Jul 23 '05 #4
david wolf wrote:
I do not agree with grtz Mark. I tried my program, it works fine. I
means it is not necessary to use
pos = tmpint.erase(po s);

simply doing
tmpint.erase(po s);

will work. Any one giving me some opnions?


Mark is right. Once you erase the 'pos' iterator, the next loop tries
to use it by dereferencing it. You simply get awfully lucky that it
stays the same on your system. 'pos' is invalidated by the call to
erase(), and dereferencing it invokes undefined behaviour. You ought
to use pos = tmpint.erase(po s);

V
Jul 23 '05 #5
I mean on Linux (red hat) system, I am using gcc. Whenever I did
tmpint.erase(po s);

pos automatically points to the element after the deleted one.

Can you tell me a case/os that this will not work?

------------------------------- Victor said -------------
'pos' is invalidated by the call to
erase(), and dereferencing it invokes undefined behaviour
------------------------------------------------------------------------------

Also, victor said above things. Could victor tell me where is it
specified to work this way?

Jul 23 '05 #6
david wolf wrote:
I mean on Linux (red hat) system, I am using gcc. Whenever I did
tmpint.erase(po s);

pos automatically points to the element after the deleted one.

Can you tell me a case/os that this will not work?
It will not work if the container you're using is not 'vector'.
------------------------------- Victor said -------------
'pos' is invalidated by the call to
erase(), and dereferencing it invokes undefined behaviour
------------------------------------------------------------------------------

Also, victor said above things. Could victor tell me where is it
specified to work this way?


I take it back. It is not invalidated, dereferencing it may not cause
undefined behaviour. Undefined behaviour only occurs if 'pos' was the
last element in the vector. However, for other containers it is true,
and if the element you're erasing is the last one, it is true. So, in
a _general_case_ it is true, then.

V
Jul 23 '05 #7

david wolf wrote:
I do not agree with grtz Mark. I tried my program, it works fine. I
means it is not necessary to use
pos = tmpint.erase(po s);

Please quote enough of the previous message to provide context for your
replies. To do so using the Google interface, click on "show options"
and use the Reply shown in the expanded header.


Brian

Jul 23 '05 #8

Victor Bazarov wrote:
david wolf wrote:
I mean on Linux (red hat) system, I am using gcc. Whenever I did
tmpint.erase(po s);

pos automatically points to the element after the deleted one.

Can you tell me a case/os that this will not work?
It will not work if the container you're using is not 'vector'.
------------------------------- Victor said -------------
'pos' is invalidated by the call to
erase(), and dereferencing it invokes undefined behaviour
------------------------------------------------------------------------------
Also, victor said above things. Could victor tell me where is it
specified to work this way?


I take it back. It is not invalidated, dereferencing it may not

cause undefined behaviour. Undefined behaviour only occurs if 'pos' was the last element in the vector. However, for other containers it is true, and if the element you're erasing is the last one, it is true. So, in a _general_case_ it is true, then.

V

I tried and found out that, even 'pos' was the last element in the
vector. If
we invoke:

tmpint.erase(po s);

pos is still defined after this erase method. After execute erase(),
pos will be point to the end of the container which means
pos=tmpint.end( ). So at least for vector, we do not have use pos =
tmpint.erase(po s), I think.

Can you help confirm this?

David

Jul 23 '05 #9
david wolf wrote:
[...]
I tried and found out that, even 'pos' was the last element in the
vector. If
we invoke:

tmpint.erase(po s);

pos is still defined after this erase method.
And how *did* you find that out?
After execute erase(),
pos will be point to the end of the container which means
pos=tmpint.end( ). So at least for vector, we do not have use pos =
tmpint.erase(po s), I think.

Can you help confirm this?


No. If 'pos == tmpint.end()' yields 'true', then you cannot use 'pos'
to do anything except compare its value to the result of calling 'end()'
or anything else you usually do with the result of calling 'end()'. The
Standard gives no guarantees that "one-past-the-end" iterator would be
dereferenceable . It therefore is not necessarily valid. There are no
special provisions in the Standard regarding 'vector' and its iterators
in that respect.

V
Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2337
by: Martin Magnusson | last post by:
I'm getting segmentation faults when trying to fix a memory leak in my program. The problem is related to lists of pointers which get passed around between objects. Here is a description of how the code works: I have a stack consisting of nodes and arguments, much like a function execution stack. In this example there are only three nodes on the stack. For each run through the loop, a copy of the current sensation is written to the...
11
1784
by: DamonChong | last post by:
Hi, I am new to c++. I recently spend an enormous among of time troubleshooting a seeminly innocuous piece of code. Although I narrow down this piece of code as the culprit but I don't understand why. Can some guru help to enlighten me? Thank you. // I created an array of pointers to object pointers: Object ** obs = new Object * ;
35
2639
by: Jon Slaughter | last post by:
I'm having a problem allocating some elements of a vector then deleting them. Basicaly I have something like this: class base { private: std::vector<object> V;
14
18579
by: cayblood | last post by:
I want to iterate through a vector and erase elements that meet a certain criteria. I know there is an algorithmic way of doing this, but first I would like to know how to do it with normal iteration. I'm am trying to do something like: vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4);
10
3223
by: Whybother | last post by:
I have this typedef map<__int64, int> Results_Map; __int64 is defined as 8 bytes ranging from -9,223,372,036.854,775,808 to 9,223,372,036.854,775,807 I have loaded it with approx 34 million hash keys and when the program is shutting down it takes forever (10+ mins) while its deleting the objects. The memory it uses according to task manager is varies from 500,000 k then
7
4345
by: JH Programmer | last post by:
Hi, is there any ways that allow us to delete an element in between? say int_val: 1 int_val: 2 int_val: 3
5
12031
by: streamkid | last post by:
i have a class table, which has a vector of records(-db). i 'm trying to remove an element, but it doesn't seem to work.. i read this http://www.cppreference.com/cppvector/erase.html] and that's the function i 've written: void table::delel( int index ) { vector< record >::iterator rm = db.begin(); for( int i = 0; i < index; i++ )
12
2718
by: subramanian100in | last post by:
Suppose class Base { public: virtual ~Test() { ... } // ... }; class Derived : public Base
19
10749
by: Daniel Pitts | last post by:
I have std::vector<Base *bases; I'd like to do something like: std::for_each(bases.begin(), bases.end(), operator delete); Is it possible without writing an adapter? Is there a better way? Is there an existing adapter? Thanks, Daniel.
0
8677
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9266
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9130
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9020
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6603
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5926
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4435
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2468
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2074
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.