【问题标题】:How to get difference between elements of two std::set<string>?如何获得两个 std::set<string> 的元素之间的差异?
【发布时间】:2011-11-03 23:09:49
【问题描述】:

所以我们有set&lt;string&gt; aset&lt;string&gt; b,我们想要得到std::set&lt;string&gt; c,其中包含代表a - b 的项目(这意味着如果我们从@987654326 中删除所有项目,则从a 中剩下的内容@,如果b 包含超过aa 中不存在的项目,我们希望让它们与数字一样简单:5-6 = 03-2 = 1)

【问题讨论】:

    标签: c++ string diff set


    【解决方案1】:

    我想你想要 std::set_difference() 来自 &lt;algorithm&gt;

    #include <iostream>
    #include <algorithm>
    #include <set>
    #include <string>
    #include <iterator>
    
    using namespace std;
    
    set<string> a;
    set<string> b;
    set<string> result;
    
    
    int main()
    {
        a.insert("one");
        a.insert("two");
        a.insert("three");
    
        b.insert("a");
        b.insert("b");
        b.insert("three");
    
        set_difference( a.begin(), a.end(), b.begin(), b.end(), inserter(result, result.begin()));
    
        cout << "Difference" << endl << "-------------" << endl;
    
        for (set<string>::const_iterator i = result.begin(); i != result.end(); ++i) {
            cout << *i << endl;
        }
    
        result.clear();
        set_symmetric_difference(a.begin(), a.end(), b.begin(), b.end(), inserter(result, result.begin()));
    
        cout << "Symmetric Difference" << endl << "-------------" << endl;
    
        for (set<string>::const_iterator i = result.begin(); i != result.end(); ++i) {
            cout << *i << endl;
        }
    
        return 0;
    }
    

    【讨论】:

      【解决方案2】:

      我想这应该可行。

      for( set<string> :: iterator it = a.begin(); it != a.end(); ++it )
      {
           set<string>:: iterator iter = find( b.begin(), b.end(), *it );
           if( iter == b.end() )
           {        // ^^^^^^^   Note: find returns b.end() if it does not find anything.
              c.insert(*iter)
           }
      }
      

      【讨论】:

      • find 在找不到元素时不返回NULL,它返回你传入的“end”迭代器(在本例中为b.end())。
      • @Martin - 感谢您的评论 :)
      【解决方案3】:

      假设你的意思是集合的差异:

      set_difference

      如果您是指元素之间的比较,则实际上无法以一般或简单的方式回答。答案将非常具体地针对 您的 问题,没有指定或明确。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        相关资源
        最近更新 更多