【问题标题】:Comparing 2 vectors and removing elements from 2nd vector that are not found in the 1st - c++ [closed]比较 2 个向量并从第 2 个向量中删除第 1 个中找不到的元素 - c++ [关闭]
【发布时间】:2020-01-27 22:52:31
【问题描述】:

我有 2 个字符串向量:

vector < string > animals = {"cat", "dog", "pig", "tiger", "monkey", "lion"}
vector < string > someAnimals = {"dog", "mouse", "snake", "monkey", "cat"}

如何比较这 2 个向量并删除 someAnimals 向量(“mouse”和“snake”)中未在动物向量中找到的元素?

【问题讨论】:

  • 如果我明白你想要什么,我认为你应该阅读this post
  • 这能回答你的问题吗? C++: subtract vectors
  • 示例代码here.
  • 请展示您到目前为止已经编写的工作,并解释您的程序究竟是如何不工作或没有产生预期的结果。您必须首先展示您的工作,并且在通过 stackoverflow.com 寻求帮助之前,它必须是真诚地真正尝试实现您的任务,而不是几行象征性的代码。有关更多信息,请参阅How to Ask 问题,获取tour,并阅读help center

标签: c++ algorithm c++11 vector find


【解决方案1】:

如果不允许对向量进行排序,则可以使用以下方法,如下面的演示程序所示。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

int main() 
{
    std::vector <std::string> animals = 
    {
        "cat", "dog", "pig", "tiger", "monkey", "lion"
    };

    std::vector <std::string> someAnimals = 
    {
        "dog", "mouse", "snake", "monkey", "cat"
    };

    auto not_present = [&animals]( const auto &s )
    {
        return 
        std::find( std::begin( animals ), std::end( animals ), s ) == std::end( animals );
    };

    someAnimals.erase( std::remove_if( std::begin( someAnimals ),
                                       std::end( someAnimals ),
                                       not_present ), std::end( someAnimals ) );

    for ( const auto &s : someAnimals )
    {
        std::cout << s << ' ';
    }
    std::cout << '\n';

    return 0;
}

程序输出是

dog monkey cat 

否则,您可以将std::binary_search 用于排序向量,如下所示。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>

int main() 
{
    std::vector <std::string> animals = 
    {
        "cat", "dog", "pig", "tiger", "monkey", "lion"
    };

    std::vector <std::string> someAnimals = 
    {
        "dog", "mouse", "snake", "monkey", "cat"
    };

    std::sort( std::begin( animals ), std::end( animals ) );
    std::sort( std::begin( someAnimals ), std::end( someAnimals ) );

    auto not_present = [&animals]( const auto &s )
    {
        return 
        not std::binary_search( std::begin( animals ), std::end( animals ), s );
    };

    someAnimals.erase( std::remove_if( std::begin( someAnimals ),
                                       std::end( someAnimals ),
                                       not_present ), std::end( someAnimals ) );

    for ( const auto &s : someAnimals )
    {
        std::cout << s << ' ';
    }
    std::cout << '\n';

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 2014-03-16
    • 1970-01-01
    相关资源
    最近更新 更多