473,387 Members | 1,485 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

deleting vector elements while looping thru it

What is the typical way to loop through a vector while deleting
certain elements during the loop process? The code below works, but I
am wondering if there is a better solution.
vector<intvTmp;
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(1);

for(int x=0; x<vTmp.size(); x++)
{
if(vTmp[x]==1)
{
vTmp.erase(vTmp.begin()+x,vTmp.begin()+x+1);
x--; //to account for new size
}
}

Apr 11 '07 #1
16 2491
ka*****@hotmail.com wrote:
What is the typical way to loop through a vector while deleting
certain elements during the loop process? The code below works, but I
am wondering if there is a better solution.
vector<intvTmp;
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(1);

for(int x=0; x<vTmp.size(); x++)
{
if(vTmp[x]==1)
{
vTmp.erase(vTmp.begin()+x,vTmp.begin()+x+1);
x--; //to account for new size
}
}
vTmp.erase(std::remove_if(vTmp.begin(), vTmp.end(), 1));

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 11 '07 #2
Victor Bazarov a écrit :
ka*****@hotmail.com wrote:
>What is the typical way to loop through a vector while deleting
certain elements during the loop process? The code below works, but I
am wondering if there is a better solution.
vector<intvTmp;
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(1);

for(int x=0; x<vTmp.size(); x++)
{
if(vTmp[x]==1)
{
vTmp.erase(vTmp.begin()+x,vTmp.begin()+x+1);
x--; //to account for new size
}
}

vTmp.erase(std::remove_if(vTmp.begin(), vTmp.end(), 1));

V
std::remove_if(vTmp.begin(), vTmp.end(), 1);
should be enough...
--
JF
Apr 11 '07 #3
none wrote:
Victor Bazarov a écrit :
>ka*****@hotmail.com wrote:
>>What is the typical way to loop through a vector while deleting
certain elements during the loop process? The code below works, but I
am wondering if there is a better solution.
vector<intvTmp;
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(1);

for(int x=0; x<vTmp.size(); x++)
{
if(vTmp[x]==1)
{
vTmp.erase(vTmp.begin()+x,vTmp.begin()+x+1);
x--; //to account for new size
}
}

vTmp.erase(std::remove_if(vTmp.begin(), vTmp.end(), 1));

V

std::remove_if(vTmp.begin(), vTmp.end(), 1);
should be enough...
remove_if doesn't actually remove things, it just reshuffles the
sequence so that the rejected elements are at the end. Having done that,
you have to tell the vector that those elements are no longer part of
the controlled sequence. You do that with erase, passing the iterator
that was returned by remove_if as the start of the sequence to be
erased, and the vector's end iterator as the end.

The proposed code isn't quite right. It should use remove (since its
third argument is a value; remove_if takes a predicate), and it's
missing an end iterator. Should be:

vTmpl.erase(std::remove(vTmp.begin(), vTmp.end(), 1), vTmp.end());

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Apr 11 '07 #4
none" <""jf\"@(none) wrote:
Victor Bazarov a écrit :
>ka*****@hotmail.com wrote:
>>What is the typical way to loop through a vector while deleting
certain elements during the loop process? The code below works,
but I am wondering if there is a better solution.
vector<intvTmp;
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(1);

for(int x=0; x<vTmp.size(); x++)
{
if(vTmp[x]==1)
{
vTmp.erase(vTmp.begin()+x,vTmp.begin()+x+1);
x--; //to account for new size
}
}

vTmp.erase(std::remove_if(vTmp.begin(), vTmp.end(), 1));

V

std::remove_if(vTmp.begin(), vTmp.end(), 1);
should be enough...
No, '1' in that case is not a valid predicate. I messed up. It
ought to be

vTmp.erase(std::remove(vTmp.begin(), vTmp.end(), 1));

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 11 '07 #5
I oversimplified my question because I take actions before I erase the
element from the vector.

Revised example code:

vector<cObjvTmp;
vector<cObjvErrors;
vTmp.push_back(obj1);
vTmp.push_back(obj2);
vTmp.push_back(obj3);
vTmp.push_back(obj4);

for(int x=0; x<vTmp.size(); x++)
{
if(vTmp[x].returnName=="NA")
{
vErrors.push_back(vTmp[x]);
vTmp.erase(vTmp.begin()+x,vTmp.begin()+x+1);
x--; //to account for new size
}
}

Apr 11 '07 #6
ka*****@hotmail.com wrote:
I oversimplified my question because I take actions before I erase the
element from the vector.

Revised example code:

vector<cObjvTmp;
vector<cObjvErrors;
vTmp.push_back(obj1);
vTmp.push_back(obj2);
vTmp.push_back(obj3);
vTmp.push_back(obj4);

for(int x=0; x<vTmp.size(); x++)
{
if(vTmp[x].returnName=="NA")
{
vErrors.push_back(vTmp[x]);
vTmp.erase(vTmp.begin()+x,vTmp.begin()+x+1);
x--; //to account for new size
}
}
struct retNameIs
{
const char* name;
retNameIs(const char* n) : name(n) {}
bool operator()(cObj const& o) {
return o.returnName == name;
}
};

...
vector<cObjvTmp;
vTmp.push_back(obj1);
vTmp.push_back(obj2);
vTmp.push_back(obj3);
vTmp.push_back(obj4);

vector<cObj>::iterator it =
std::remove_if(vTmp.begin(), vTmp.end(), retNameIs("NA"));
vector<cObjvErrors(it, vTmp.end());
vTmp.erase(it, vTmp.end());

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 11 '07 #7
On Wed, 11 Apr 2007 11:17:51 -0400, Pete Becker wrote:
>remove_if doesn't actually remove things, it just reshuffles the
sequence so that the rejected elements are at the end.
The Standard doesn't specify that 'rejected' elements can be found at
the end of the sequence.

--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
Apr 11 '07 #8
Roland Pibinger wrote:
On Wed, 11 Apr 2007 11:17:51 -0400, Pete Becker wrote:
>remove_if doesn't actually remove things, it just reshuffles the
sequence so that the rejected elements are at the end.

The Standard doesn't specify that 'rejected' elements can be found at
the end of the sequence.
The algorithm is called "in-place". What besided "reshuffles" can
that mean? 'remove_if' returns the iterator that points to the _end_
of the resulting sequence. What besides placing the "removed"
elements of the sequence beyond the new end could it mean? IOW, if
you apply all the definitions of what 'remove' ('remove_if') does,
it results in moving the rejected elements within the same sequence
beyond what it returns as new end of the sequence.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 11 '07 #9
Victor Bazarov wrote:
Roland Pibinger wrote:
>On Wed, 11 Apr 2007 11:17:51 -0400, Pete Becker wrote:
>>remove_if doesn't actually remove things, it just reshuffles the
sequence so that the rejected elements are at the end.
The Standard doesn't specify that 'rejected' elements can be found at
the end of the sequence.

The algorithm is called "in-place". What besided "reshuffles" can
that mean?
Actually, he's right, although it's irrelevant to this particular
discussion. remove and remove_if leave whatever junk they fell like at
the end of the original sequence. Typically it's the elements that were
there before, not necessarily the ones that were rejected. So for the
example under discussion, the tail of the array would not hold all 1's
unless they were there to begin with. Typically you'd see a vector
holding, say, 1,3,1,5,7,1 turning into 3,5,7,5,7,1. The last three
elements are the leftovers.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Apr 11 '07 #10
Pete Becker wrote:
Victor Bazarov wrote:
>Roland Pibinger wrote:
>>On Wed, 11 Apr 2007 11:17:51 -0400, Pete Becker wrote:
remove_if doesn't actually remove things, it just reshuffles the
sequence so that the rejected elements are at the end.
The Standard doesn't specify that 'rejected' elements can be found at
the end of the sequence.

The algorithm is called "in-place". What besided "reshuffles" can
that mean?

Actually, he's right, although it's irrelevant to this particular
discussion. remove and remove_if leave whatever junk they fell like at
the end of the original sequence. Typically it's the elements that were
there before, not necessarily the ones that were rejected. So for the
example under discussion, the tail of the array would not hold all 1's
unless they were there to begin with. Typically you'd see a vector
holding, say, 1,3,1,5,7,1 turning into 3,5,7,5,7,1. The last three
elements are the leftovers.
Forgot to mention: those last two sentences refer to the problem under
discussion, i.e. removing 1's from the vector.

Oh, and the "in-place" is in distinction to "copying", which leaves the
original sequence intact.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Apr 11 '07 #11
Pete Becker wrote:
Pete Becker wrote:
>Victor Bazarov wrote:
>>Roland Pibinger wrote:
On Wed, 11 Apr 2007 11:17:51 -0400, Pete Becker wrote:
remove_if doesn't actually remove things, it just reshuffles the
sequence so that the rejected elements are at the end.
The Standard doesn't specify that 'rejected' elements can be found
at the end of the sequence.

The algorithm is called "in-place". What besided "reshuffles" can
that mean?

Actually, he's right, although it's irrelevant to this particular
discussion. remove and remove_if leave whatever junk they fell like
at the end of the original sequence. Typically it's the elements
that were there before, not necessarily the ones that were rejected.
So for the example under discussion, the tail of the array would not
hold all 1's unless they were there to begin with. Typically you'd
see a vector holding, say, 1,3,1,5,7,1 turning into 3,5,7,5,7,1. The
last three elements are the leftovers.

Forgot to mention: those last two sentences refer to the problem under
discussion, i.e. removing 1's from the vector.

Oh, and the "in-place" is in distinction to "copying", which leaves
the original sequence intact.
So, I was wrong.

To be entirely correct, instead of extracting the "left-overs" after
'remove_if', I ought to use 'copy_if' along with 'erase'. Except there
is no 'copy_if', is there?

So, there is no decent way.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 11 '07 #12
Victor Bazarov wrote:
To be entirely correct, instead of extracting the "left-overs" after
'remove_if', I ought to use 'copy_if' along with 'erase'. Except there
is no 'copy_if', is there?
You could use remove_copy_if with a negated predicate. remove_copy_if
will copy a range, removing those that match the predicate. So if you
negate the predicate, you will copy only those that do match the
original predicate.

Anyone know if C++0x is going to have copy_if?
Apr 11 '07 #13
Victor Bazarov wrote:
>
To be entirely correct, instead of extracting the "left-overs" after
'remove_if', I ought to use 'copy_if' along with 'erase'. Except there
is no 'copy_if', is there?

So, there is no decent way.
No, what you had was basically right. remove or remove_if, followed by
erase to kill off the leftovers. So remove(begin(), end(), 1) turns
1,3,1,5,7,1 into 3,5,7,x,x,x (where the x's are unspecified, but most
likely are 5,7,1) and returns an iterator pointing to the first x.
erase(iterator, end()) removes the junk at the end.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Apr 12 '07 #14
Pete Becker wrote:
Victor Bazarov wrote:
>>
To be entirely correct, instead of extracting the "left-overs" after
'remove_if', I ought to use 'copy_if' along with 'erase'. Except
there is no 'copy_if', is there?

So, there is no decent way.

No, what you had was basically right. remove or remove_if, followed by
erase to kill off the leftovers. So remove(begin(), end(), 1) turns
1,3,1,5,7,1 into 3,5,7,x,x,x (where the x's are unspecified, but most
likely are 5,7,1) and returns an iterator pointing to the first x.
erase(iterator, end()) removes the junk at the end.
Right. I know. The OP also wanted to extract the removed elements
into a separate vector. That's where 'copy_if' would come handy.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 12 '07 #15
Victor Bazarov wrote:
Pete Becker wrote:
>Victor Bazarov wrote:
>>To be entirely correct, instead of extracting the "left-overs" after
'remove_if', I ought to use 'copy_if' along with 'erase'. Except
there is no 'copy_if', is there?

So, there is no decent way.
No, what you had was basically right. remove or remove_if, followed by
erase to kill off the leftovers. So remove(begin(), end(), 1) turns
1,3,1,5,7,1 into 3,5,7,x,x,x (where the x's are unspecified, but most
likely are 5,7,1) and returns an iterator pointing to the first x.
erase(iterator, end()) removes the junk at the end.

Right. I know. The OP also wanted to extract the removed elements
into a separate vector. That's where 'copy_if' would come handy.
Okay, I see what you're saying.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
Apr 12 '07 #16
On Apr 11, 4:50 pm, "kafe...@hotmail.com" <kafe...@hotmail.comwrote:
What is the typical way to loop through a vector while deleting
certain elements during the loop process? The code below works, but I
am wondering if there is a better solution.
vector<intvTmp;
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(2);
vTmp.push_back(1);
vTmp.push_back(1);
for(int x=0; x<vTmp.size(); x++)
{
if(vTmp[x]==1)
{
vTmp.erase(vTmp.begin()+x,vTmp.begin()+x+1);
x--; //to account for new size
}
}
Others have pointed out the solution using remove or remove_if,
which handles this specific case. More generally, if you're
possibly doing a number of other things, or for some other
reason prefer writing the loop yourself:

std::vector<int>::iterator current = v.begin() ;
while ( current != v.end() ) {
// ...
if ( shouldBeDeleted ) {
current = v.erase( current ) ;
} else {
++ current ;
}
}

can be used. (Note that in the case of vector, this is likely
to result in a lot more copying than using std::remove. If the
container is a list, however, it's probably more efficient. And
of course, unless the container is very big, and the types
expensive to copy, it generally doesn't matter.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 12 '07 #17

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

Similar topics

6
by: Matthias | last post by:
Hi, say I have a vector v1: std::vector<SomeType> v1; and I need a vector v2 of pointers to v1's elements: std::vector<SomeType*> v2;
1
by: Varun Kacholia | last post by:
I apologize if there exists a standard way of deleting multiple elements from a STL hash_multiset (or even multiset for that matter) that I am unaware of. The problem, I see, with multisets is...
7
by: linq936 | last post by:
Hi, The following is a psudo code to describe my question: vector<int> ints; vector<int>::iterator itr; while (itr != ints.end()){ int j = some_function(*i); if (j>0){ ints.push_back(j); }
4
by: Christian Bruckhoff | last post by:
Hi. Is there a possibility to delete elements out of a vector? At the moment i do it by copying all needed elements to another vector. After clearing the old vector i copy them back element by...
1
by: pds79 | last post by:
Hi everyone, I'm a newbie to the forum. I have an issue and was hoping to get some assistance/ideas: Im trying to read a XML file into two record sets. I can acheive looping through the...
1
by: eusko | last post by:
for example vec = new int; then we input the values of vector elements if we decided to change the vector size, is it possible to do it without deleting the existing values of the vector...
3
by: Andy | last post by:
Hello, I have the following situation: Thread A is allocating a dataset, doing some low-level calculations and storing a pointer to the dataset in a std::list via push_back. Thread B should...
5
by: Etrex | last post by:
Hello, This is my first attempt at a c++ program, and it is a long post, please bear with me. I'm trying to read in a text file containing a firewall log, make the information...
3
by: deepak1905 | last post by:
Hi, I am working on c++ in a linux system ( Fedora core 4 ), kernel version - 2.6.11-1.1369_FC4 gcc version - 4.0.0 20050519 ( Red Hat 4.0.0-8 ) In my code i am creating a vector to store...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...

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.