21xrx.com
2024-09-20 05:51:58 Friday
登录
文章检索 我的文章 写文章
C++实现去除重复元素的方法:使用make_unique函数
2023-06-24 02:39:02 深夜i     --     --
C++ 去除重复元素 make_unique函数

C++是一门强大的编程语言,在我们使用它的时候,有时候需要去除重复元素。那么如何使用C++来实现去除重复元素的方法呢?这里我们可以利用make_unique函数来实现这一功能。

make_unique函数是C++11中的一个新的函数,主要用于创建一个动态分配的对象,返回一个指向该对象的unique_ptr对象。使用make_unique可以避免指针的泄漏,并提供了更简洁的语法。

当我们要去除重复元素时,可以使用STL中的set容器,它可以自动将元素从小到大排序,并且不会存储重复元素。我们可以将去重后的元素插入到一个新的vector中,这样就可以实现去重功能。

下面是一个示例代码:


#include <iostream>

#include <vector>

#include <set>

#include <memory>

int main()

{

  std::vector<int> arr = 2;

  std::set<int> s(arr.begin(), arr.end());

  std::vector<int> newArr;

  for (const auto &i : s)

  {

    newArr.push_back(i);

  }

  std::unique_ptr<std::vector<int>> pNewArr = std::make_unique<std::vector<int>>(std::move(newArr));

  // 输出去重后的元素

  for (const auto &i : *pNewArr)

  

    std::cout << i << " ";

  

  std::cout << std::endl;

  return 0;

}

在上面的代码中,我们首先定义了一个包含重复元素的vector,然后使用set容器去重。接着,我们将去重后的元素插入到新的vector中,并使用make_unique函数创建了一个动态分配的vector对象。最后,我们可以通过遍历该vector对象输出去重后的元素。

总结:

使用make_unique函数可以避免指针泄漏,提供更简洁的语法,而set容器可以自动去重并排序。这样,我们就可以通过C++实现去除重复元素的方法了。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章