473,573 Members | 5,052 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2503
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<intvTm p;
vTmp.push_bac k(1);
vTmp.push_bac k(2);
vTmp.push_bac k(1);
vTmp.push_bac k(2);
vTmp.push_bac k(1);
vTmp.push_bac k(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.b egin(), 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<intvTm p;
vTmp.push_bac k(1);
vTmp.push_bac k(2);
vTmp.push_bac k(1);
vTmp.push_bac k(2);
vTmp.push_bac k(1);
vTmp.push_bac k(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.be gin(), 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<cObjvErr ors;
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=="N A")
{
vErrors.push_ba ck(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<cObjvErr ors;
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=="N A")
{
vErrors.push_ba ck(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>::i terator it =
std::remove_if( vTmp.begin(), vTmp.end(), retNameIs("NA") );
vector<cObjvErr ors(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

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

Similar topics

6
3106
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
2014
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 that you cannot obtain info to uniquely identify an element (eg: indices in a vector, or key in set/hash_set). Hence what I'd like to do is iterate...
7
6586
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
2461
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 element. Regards! Christian
1
16644
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 first level element but i can not loop the the second level (child elements), any ideas?? I need to be able to loop thru each patient record and read...
1
1401
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 elements? Thanks!
3
3715
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 retrieve the pointer to the first dataset in the list, remove it from the list, and do some high level analysis. The problem now is, how do I...
5
2453
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 searchable by an element (protocol, remote ip etc). The file is of known max width (65) containing 8 columns of known max size. The columns are seperated by...
3
2657
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 pointers of type structure "SAMPLE_TABLE_STRUCT" ( size of this structure is 36 bytes ). I create an instance of structure "SAMPLE_TABLE_STRUCT" using...
0
7789
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7707
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...
0
8215
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...
0
8086
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6432
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5605
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...
0
3737
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...
0
3743
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1048
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...

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.