C/C++ C++ trouble erasing elements from a <vector>

AI Thread Summary
The discussion centers on the challenge of removing elements from a C++ STL vector. The user is trying to create a new vector, V_S, which contains elements from vector V that are not present in vector S. The initial approach involves copying V to V_S and then attempting to erase elements found in S. However, this leads to an error, likely due to incorrect usage of the erase method. The solution suggested involves iterating through V_S and checking if each element exists in S, using an appropriate method to remove elements by passing an iterator to the erase function, rather than trying to erase elements directly. This highlights the importance of understanding iterator usage in C++ STL operations.
FrostScYthe
Messages
80
Reaction score
0
Hi, I've been having trouble erasing elements from a <vector> (that is from the STL of C++)

See I declared 2 vectors V and S, V contains let's say all the elements, while S is a solution set which contains some elements that are classified... well yeah...

I need to create V-S which is a vector that has all the elements in V that are not in S.. I was planning on doing this by making a copy of V into V_S and then erasing every element I add to S from V_S.

sort of like this:

S.push_back(x);
V_S.erase(x);

I get an error... Why?
 
Technology news on Phys.org
What kind of error do you get? Compilation error?
I would suggest you to iterate with a loop through all the elements of V_S and check with a vector method (I think called exists()) if each element also exists in vector S. If yes just remove them.
 
You have to pass an iterator to erase, not the element you want to remove.
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...

Similar threads

Replies
23
Views
2K
Replies
25
Views
2K
Replies
5
Views
3K
Replies
4
Views
1K
Replies
7
Views
3K
Replies
3
Views
2K
Replies
1
Views
4K
Back
Top