Difference between clear() and erase() methods of a vector in c++?
19,190
Solution 1
clear()
removes all elements from the vector leaving behind a vector of size zero while erase()
deletes a single element or a range of elements from the vector.
Solution 2
Erase takes a parameter - the thing to erase. clear dumps the lot.
As per the manual http://en.cppreference.com/w/cpp/container/vector
Author by
user2481909
Updated on June 15, 2022Comments
-
user2481909 almost 2 years
Following is the main function of my program, I could not find any difference between clear() and erase() of vector, then why in following code I am getting diferent results when I use erase() instead of clear()?
int main() { int notest, N, temp; long long sum, profit; int count; vector<int> S; S.reserve(50009); cin>>notest; for(int test=0; test<notest; test++) { profit = 0; cin>>N; for(int i=0; i<N; i++) { cin>>temp; S.push_back(temp); } DO SOME THING HERE S.clear(); } }
Here clear() is not producing the desired results, but when I use erase I get desired results, why?