A possible improvement. Combine "erase" and "count" together to save some time.

#include <unordered_set>
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
if (nums1.empty() || nums2.empty()){
return std::vector<int>();
}
std::unordered_set<int> set{nums1.cbegin(), nums1.cend()};
std::vector<int> intersections;
for (auto n: nums2){
if (set.erase(n) > 0){ // if n exists in set, then 1 is returned and n is erased; otherwise, 0.
intersections.push_back(n);
}
}
return intersections;
}
};

OMG I considered this problem more complicated because I think we need to consider the count of each arrays. I mean if nums1 has two '2', the nums2 must have exactly two '2' for intersection. So I used HashMap to store element and count by Key and values.

You should compare with the previous one in its own vector, not ans.back().
think about this example.
[1,3,3]
[1,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3]
I wish the program to directly skip these 2s, but your code will not. I know it can process 3s correctly.

@kushao1267 Sorry about the wrong typing, it's not for the test case problem. Anyway I've updated it changing the are to nums1 in the following two places: