C++中两个指针向量的减法和相交

Amr*_*mar 1 c++ stdvector

我有两个向量,指向我的自定义类对象.
这两个向量中的指针不指向同一个对象,但存储在对象中的值是相同的.

我的自定义类结构是:


Class Item
{
   string ItemId;
   string ItemDescription;
   float ItemPrice;
}
第一矢量(V1)具有n个条目,第二矢量(V2)具有m个条目(n> m).

我要执行两个操作:

  • 获取一个在V1V2中都有共同对象的向量.通常,我的意思是说元素的ItemId是相同的.(可以称为V1和V2的交点).

  • 获取具有V2中不存在的元素的向量.(可以称为V1-V2).

    如何以有效的方式做到这一点?

  • Gob*_*0st 5

    以下是如何使用STL set_intersection和set_difference来获取所需内容的示例:

    class Item
    {
    public:
        Item(int i):ItemId(i){}
    
       int ItemId;
       string ItemDescription;
       float ItemPrice;
    
       bool operator<(const Item& rhs)
       {
           return ItemId < rhs.ItemId;
       }
       bool operator==(const Item& rhs)
       {
           return ItemId == rhs.ItemId;
       }
    };
    
    int main()
    {
        std::vector<Item> myvec1;
        myvec1.push_back(Item(1));
        myvec1.push_back(Item(2));
        myvec1.push_back(Item(1));
        myvec1.push_back(Item(10));
        myvec1.push_back(Item(5));
        myvec1.push_back(Item(3));
        myvec1.push_back(Item(10));
    
    
        std::vector<Item> myvec2;
        myvec2.push_back(Item(10));
        myvec2.push_back(Item(1));
        myvec2.push_back(Item(10));
        myvec2.push_back(Item(1));
        myvec2.push_back(Item(3));
    
        std::sort(myvec1.begin(), myvec1.end());
        std::sort(myvec2.begin(), myvec2.end());
    
        myvec1.erase(std::unique(myvec1.begin(), myvec1.end()), myvec1.end());
        myvec2.erase(std::unique(myvec2.begin(), myvec2.end()), myvec2.end());
    
        std::vector<Item> myvec3; //Intersection of V1 and V2
        std::vector<Item> myvec4; //V1-V2
        set_intersection(myvec1.begin(),myvec1.end(), myvec2.begin(),myvec2.end(), std::back_inserter(myvec3)); //myvec3: 1 3 10
        set_difference(myvec1.begin(),myvec1.end(), myvec2.begin(),myvec2.end(), std::back_inserter(myvec4));   //myvec4: 2 5 
    }
    
    Run Code Online (Sandbox Code Playgroud)