我如何得到字符共同的两个向量在C + +? [英] How do I get characters common to two vectors in C++?

查看:133
本文介绍了我如何得到字符共同的两个向量在C + +?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较两个向量对象,并返回一个包含所有出现在两个向量中的字符的向量。

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

一些非常复杂的手动方法,它将第一个向量中的每个字符与第二个向量中的每个字符进行比较,如果它们匹配,则使用if将其添加到第三个向量(将被返回)。

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.

推荐答案

我想你正在寻找 std :: set_intersection 。源向量必须排序。如果你不关心你的输出向量的顺序,你总是可以运行它的源向量的排序副本。

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.

和BTW,手动天真的方式isn非常复杂。给定两个源向量 s1 s2 ,以及目标向量 dest ,你可以这样编写:

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);
    }
}

您有很多选项 find 步骤,取决于您选择的数据结构。

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

这篇关于我如何得到字符共同的两个向量在C + +?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆