ฉันมีคอนเทนเนอร์ STL สองคอนเทนเนอร์ที่ฉันต้องการรวม โดยลบองค์ประกอบใดๆ ที่ปรากฏมากกว่าหนึ่งครั้ง ตัวอย่างเช่น:
typedef std::list<int> container;
container c1;
container c2;
c1.push_back(1);
c1.push_back(2);
c1.push_back(3);
c2.push_back(2);
c2.push_back(3);
c2.push_back(4);
container c3 = unique_merge(c1, c2);
// c3 now contains the following 4 elements:
// 1, 2, 3, 4
std::unique ดูเหมือนจะมีไว้สำหรับองค์ประกอบที่อยู่ติดกันเท่านั้น และในกรณีของฉัน คอนเทนเนอร์อาจอยู่ในลำดับใดก็ได้ ฉันสามารถทำกลอุบาย std::set ได้บ้าง ฉันเดาว่า:
container unique_merge(const container& c1, const container& c2)
{
std::set<container::value_type> s;
BOOST_FOREACH(const container::value_type& val, c1)
s.insert(val);
BOOST_FOREACH(const container::value_type& val, c2)
s.insert(val);
return container(s.begin(), s.end());
}
มีวิธีที่ดีกว่าหรือฉันพลาดบางสิ่งบางอย่างที่ชัดเจนหรือไม่?