gpt4 book ai didi

c++ - C++ 中两个指针 vector 的减法和交集

转载 作者:太空宇宙 更新时间:2023-11-03 10:34:26 25 4
gpt4 key购买 nike

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

我自定义的类结构是:


Class Item
{
string ItemId;
string ItemDescription;
float ItemPrice;
}
第一个 vector ( V1) 有 n 个条目,第二个 vector ( V2) 有 m 个条目 < em>(n>m)。

我必须执行两个操作:

  • 得到一个在V1V2中都有共同对象的 vector 。 所谓通用,是指元素的 ItemId 相同。(可以称为V1 和 V2 的交集)。< p>

  • 获取一个 vector ,其中包含 V2 中不存在的元素。 (可以称为 V1-V2)。

    如何高效地做到这一点??

  • 最佳答案

    这里是如何使用 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
    }

    关于c++ - C++ 中两个指针 vector 的减法和交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6955578/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com