I'm new to C++ programming. I want to make a code that shows elements which two char vectors have and do not have in common.
I started by creating two string by cin and then pass them to vectors. But now I don't know how to compare the char elements of both vectors, or even how to get to those elements. I tried treating them as if they were int and using set_difference, but none of that worked.
I would love to hear any recommendations on how to complete my code.
Here is the part of my code that actually can run:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main(){
string s1, s2;
vector<int> diff;
cin >> s1;
cin >> s2;
vector<char> v1(s1.begin(), s1.end());
vector<char> v2(s2.begin(), s2.end());
return 0;
}
First, you don't have to create vectors - you can work on strings as well. Also, the vector containing different characters should contain
chars, notints, so:Now, if you want to check if the characters in
s1are different or same tos2, you have to compare each element ins1with each element ins2.At this point
diffcontains all elements ofs1thats2doesn't contain andsamecontains common elements. You need to append elements ofs2thats1doesn't contain, too.This code snippet is very similar to the previous one - the only differences are that
s2is now the outer loop ands1the inner one and elements that are same aren't added to thesamevector as they have already been added there.You may not be familiar with the
for(const auto& it : s1)syntax. Here it is basically equivalent tofor(size_t it; it < s1.size(); ++it)(but they are pretty much different in general). For more detail google "range-based for loop".As you can see comparing two unsorted arrays (in this case
std::strings, which are arrays of chars under the hood) is very inefficient. A much better container for this situation would bestd::set. It has its downsides as well, for example the elements must not repeat (if you try to insert an already existing element, nothing hapens), yet it suits this case perfectly. Google std::set to use it consciously.Final code: