Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get characters common to two vectors in C++?

I am trying to compare two vector objects, and return a single vector containing all the chars which appear in both vectors.

How would I go about this without writing some horribly complex manual method which compares every char in the first vector to every char in the second vector and using an if to add it to a third vector (which would be returned) if they match.

Maybe my lack of real experience with vectors is making me imagine this will be harder than it really is, but I suspect there is some simplier way which I have been unable to find through searching.

like image 852
Drake Avatar asked Mar 08 '10 19:03

Drake


People also ask

How do you find the common element between two vectors?

To find common elements between two vectors, we can use set_intersection() function, it accepts the iterators of both vectors pointing to the starting and ending ranges and an iterator of result vector (in which we store the result) pointing to the starting position and returns an iterator pointing to the end of the ...

How do you count the number of occurrences of an element in a vector in C++?

std::count() returns number of occurrences of an element in a given range. Returns the number of elements in the range [first,last) that compare equal to val.

How do you find the common element in two vectors in R?

To do this intersect() method is used. It is used to return the common elements from two objects. where, vector is the input data. If there are more than two vectors then we can combine all these vectors into one except one vector.

Are duplicates allowed in vector?

No, it is only bad if the source data is particularly large and unlikely to have any duplicates.


2 Answers

If I had to do this on two unsorted vectors (without library help), I think I'd add all the elements of one to a hashtable then iterate through the second looking up each--should be more efficient than sorting both lists first as well.

like image 98
Bill K Avatar answered Oct 24 '22 10:10

Bill K


I think you're looking for std::set_intersection. The source vectors have to be sorted though. If you don't care about the order of your output vector, you could always run it on sorted copies of your source vectors.

And BTW, the manual naive way isn't horribly complex. Given two source vectors s1 and s2, and a destination vector dest, you could write something that looks like this:

for (std::vector<char>::iterator i = s1.begin(); i != s1.end(); ++i)
{
    if (std::find(s2.begin(), s2.end(), *i) != s2.end())
    {
        dest.push_back(*i);
    }
}

You have a lot of options for the find step depending on your choice of data structure.

like image 25
Michael Kristofik Avatar answered Oct 24 '22 11:10

Michael Kristofik