我有两个指向我的自定义类对象的指针。
这两个 vector 中的指针没有指向同一对象,但是存储在这些对象中的值是相同的。
我的自定义类结构为:
Class Item
{
string ItemId;
string ItemDescription;
float ItemPrice;
}
第一个 vector ( V1 )具有n个条目,第二个 vector ( V2 )具有m个条目(n> m)。我必须执行两项操作:
如何有效地做到这一点?
最佳答案
这是如何使用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/