C++ trouble erasing elements from a <vector>

  • Context: C/C++ 
  • Thread starter Thread starter FrostScYthe
  • Start date Start date
  • Tags Tags
    C++ Elements Vector
Click For Summary
SUMMARY

The discussion focuses on the challenges of erasing elements from a C++ using the Standard Template Library (STL). The user attempts to create a new vector, V_S, that contains elements from vector V that are not present in vector S. The suggested solution involves iterating through V_S and using the erase method with an iterator instead of directly passing the element to be removed. This approach resolves the compilation error encountered when trying to erase elements incorrectly.

PREREQUISITES
  • Understanding of C++ Standard Template Library (STL)
  • Familiarity with and its methods
  • Knowledge of iterators in C++
  • Basic error handling in C++
NEXT STEPS
  • Learn about C++ iterators and their usage
  • Research the erase method and its requirements in STL
  • Explore algorithms for set difference in C++
  • Study error handling techniques in C++ for better debugging
USEFUL FOR

C++ developers, software engineers, and students learning about STL and vector manipulation who are looking to improve their understanding of element removal techniques in vectors.

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.
 

Similar threads

  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 25 ·
Replies
25
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
13
Views
4K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 14 ·
Replies
14
Views
7K