473,796 Members | 2,676 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to remove elements of vector by index

Hello

I have a vector<int(aRem ovecoll) which is a list of the indexes to
be removed from another vector. The other vecotr contains an object -
I will call it SomeObject. So the other vecotr is a
vector<SomeObje ct>.

I have created a function like this so far:

UINT uNumElements = aRemoveColl.Get Size();
vector<T>::reve rse_iterator obCurrent = rbegin(); // work from
end back
for (UINT nLoop = uNumElements; nLoop != 0; nLoop--)
{
// Work from end of vecotr to beginning so that iterators are
always valid
intuIndex;
aRemoveColl.Get At(nLoop, uIndex);
advance(obCurre nt, uIndex);
erase(obCurrent );
}

My thinking is that I need to erase from the end backwards because
otherwise the iterator will become invalid. But then advance doesn't
see right. Is there a backward? Or should I be doing this totally
differently?

Jul 23 '07 #1
2 2382
On 23 ec, 12:19, Angus <anguscom...@gm ail.comwrote:
Hello

I have a vector<int(aRem ovecoll) which is a list of the indexes to
be removed from another vector. The other vecotr contains an object -
I will call it SomeObject. So the other vecotr is a
vector<SomeObje ct>.

I have created a function like this so far:

UINT uNumElements = aRemoveColl.Get Size();
vector<T>::reve rse_iterator obCurrent = rbegin(); // work from
end back
for (UINT nLoop = uNumElements; nLoop != 0; nLoop--)
{
// Work from end of vecotr to beginning so that iterators are
always valid
intuIndex;
aRemoveColl.Get At(nLoop, uIndex);
advance(obCurre nt, uIndex);
erase(obCurrent );
}

My thinking is that I need to erase from the end backwards because
otherwise the iterator will become invalid. But then advance doesn't
see right. Is there a backward? Or should I be doing this totally
differently?
Hi.

You can use iterators, for example:
std::vector<int v;

// Here fill v with some values
// ...

v.erase(v.begin () + 4, v.begin() + 10); // Removes elements from index
4 to 10

Jul 23 '07 #2
On Jul 23, 12:19 pm, Angus <anguscom...@gm ail.comwrote:
I have a vector<int(aRem ovecoll) which is a list of the indexes to
be removed from another vector. The other vecotr contains an object -
I will call it SomeObject. So the other vecotr is a
vector<SomeObje ct>.
I have created a function like this so far:
UINT uNumElements = aRemoveColl.Get Size();
vector<T>::reve rse_iterator obCurrent = rbegin(); // work from
end back
for (UINT nLoop = uNumElements; nLoop != 0; nLoop--)
{
// Work from end of vecotr to beginning so that iterators are
always valid
intuIndex;
aRemoveColl.Get At(nLoop, uIndex);
advance(obCurre nt, uIndex);
erase(obCurrent );
}
My thinking is that I need to erase from the end backwards because
otherwise the iterator will become invalid.
Not really.
But then advance doesn't see right.
I don't really understand your code. What's GetAt, for example?
The easiest way to do this would be something like:

for ( std::vector< int >::const_iterat or it =
aRemoveColl.beg in() ;
it != aRemoveColl.end () ;
++ it ) {
data.erase( data.begin() + *it ) ;
}

You don't remove anything from the vector you're iterating over,
so there is no problem.

Note however that this is O(n*m), with n the number of elements
of data, and m the number of elements to be erased. So you
might want to consider generating into a new vector, or even
defining a predicate for remove_if, and using it. (If
aRemoveColl is sorted, something along the lines of:

class SomeObject ;

class IndexIn
{
public:
typedef std::vector< size_t >
IndexTable ;
typedef std::vector< size_t >::const_iterat or
IndexIter ;

explicit IndexIn( IndexTable const& indexes )
: myImpl( new Impl( indexes.begin() , indexes.end() ) )
{
}
bool operator()( SomeObject const& ) const
{
return (*myImpl)() ;
}

private:
class Impl
{
public:
Impl( IndexIter begin, IndexIter end )
: myCurrent( begin )
, myEnd( end )
, myIndex( 0 )
{
}
bool operator()()
{
bool result
= myCurrent != myEnd && myIndex == *myCurrent ;
++ myIndex ;
if ( result ) {
++ myCurrent ;
}
return result ;
}
private:
IndexIter myCurrent ;
IndexIter myEnd ;
size_t myIndex ;
} ;

boost::shared_p tr< Impl>
myImpl ;
} ;

// ...
v.erase( std::remove_if( v.begin(), v.end(),
IndexIn( aRemoveColl ) ),
v.end() ) ;

should do the trick.)
Is there a backward? Or should I be doing this totally
differently?
I'd do it differently.

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

Jul 24 '07 #3

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

Similar topics

11
2747
by: koperenkogel | last post by:
Dear cpp-ians, I am working with a vector of structures. vector <meta_segment> meta_segm (2421500); and the structure look like: struct meta_segment { float id; float num;
9
3615
by: david wolf | last post by:
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
8
1703
by: imutate | last post by:
I have a std::vector with each element being a class, I push_back elements and then store values in the class object, later I look at these objects and the values are null. In essence: class celement { public: int x; ...
5
2656
by: Wing | last post by:
Hello, I am thinking an efficient way to remove all the elements (says they are less than 10) from a container vector<int>. Any suggestion? Thank you.
6
3406
by: happyvalley | last post by:
Hi, I want to remove some elements from a vector, the following code doesn't work, seems it doesn't allow me to remove an element when iterating the vector. (make sense), just wonder, how to do this? thank vector<intIntVec; vector<int>::iterator intIterator; for(int i=0; i<10;i++) IntVec.push_back(i);
7
1666
by: mohammaditraders | last post by:
Write a program which overloads a binary Minus (+) operator, The program will contain a class Matrix, This class will contain a private data member Array which store int values. The class will further contain a Default constructor, get() function which takes values for array from the user and also contain a Display function witch display the array on the screen, In main function create three objects Mat1, Mat2, Mat3 of this class, first...
6
2064
jlandbw04
by: jlandbw04 | last post by:
Okay. Here's the deal. I have this assignment for college that has me completely puzzled. I need this assignment to do the following: 1. input 12 integers into an array from the user. 2. output the numbers back to the screen showing what the user input. 3. ask the user what integer they would like to remove. 4. use a loop to remove ALL occurrance of that integer, and the output the new numbers back to the screen for the user to see the...
19
6082
by: arnuld | last post by:
/* C++ Primer - 4/e * chapter 4- Arrays & Pointers, exercise 4.28 * STATEMENT * write a programme to read the standard input and build a vector of integers from values that are read. allocate an array of the same size as the vector and copy elements from the vector into the array */
3
2247
by: n.torrey.pines | last post by:
I'd like to be able to view two contiguous elements of a vector as a pair. Assuming I'm not accessing the last element, of course, and the element type is not bool, when is it safe to do so, from the language definition point of view? const pr& p = *(const pr*)(&v); // pr - either std::pair or hand-defined pair of elements
0
10452
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
10221
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
10169
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,...
0
9050
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7546
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
6785
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();...
1
4115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
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.