當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ std swap()用法及代碼示例

C++ std swap(set) 是 C++ 中 set 的非成員函數。這用於交換(或交換)兩個集合(即 x 和 y)的內容,但盡管大小可能不同,但兩個集合的類型必須相同。

用法

template <class T, class Compare, class Alloc>
  void swap (set<T,Compare,Alloc>& x, set<T,Compare,Alloc>& y);

參數

x: 首先設置對象。

y:第二組相同類型的對象。

返回值

複雜度

恒定。

迭代器有效性

引用兩個容器中元素的所有迭代器、引用和指針都保持有效。

請注意,結束迭代器不引用元素並且可能會失效。

數據競爭

容器 x 和 y 都被修改。

調用不會訪問包含的元素。

異常安全

該函數不會拋出異常。

例子1

讓我們看一個簡單的例子,將一個集合的元素交換到另一個:

#include <iostream>
#include <set>

using namespace std;

int main(void) {
   set<char> m1 = {'a','b','c','d'};

   set<char> m2;

   swap(m1, m2);

   cout << "Set contains following elements" << endl;

   for (auto it = m2.begin(); it != m2.end(); ++it)
      cout << *it<< endl;

   return 0;
}

輸出:

Set contains following elements
a
b
c
d

在上麵的例子中,集合 m1 有五個元素,而 m2 是空的。當您將 m1 交換為 m2 時,m1 的所有元素都將交換為 m2。

例子2

看一個簡單的例子來交換兩個集合的內容:

#include <iostream>
#include <set>

using namespace std;

int main ()
{
  set<int> set1,set2;

  set1= {100,200};

  set2 = {110, 220, 330};

  swap(set1,set2);

  cout << "set1 contains:\n";
  for (set<int>::iterator it=set1.begin(); it!=set1.end(); ++it)
    cout << *it<< '\n';

  cout << "set2 contains:\n";
  for (set<int>::iterator it=set2.begin(); it!=set2.end(); ++it)
    cout << *it<< '\n';

  return 0;
}

輸出:

set1 contains:
110
220
330
set2 contains:
100
200

在上麵的例子中,兩個集合即 set1 和 set2 的內容相互交換。

例子3

讓我們看一個簡單的例子來交換兩個集合的內容:

#include <iostream>
#include <set>

using namespace std;

 int main ()
{
  int myints[]={12,75,10,32,20,25};
  set<int> first (myints,myints+3);     // 10,12,75
  set<int> second (myints+3,myints+6);  // 20,25,32

  swap(first,second);

  cout << "first contains:";
  for (set<int>::iterator it=first.begin(); it!=first.end(); ++it)
    cout << ' ' << *it;
  cout << '\n';

  cout << "second contains:";
  for (set<int>::iterator it=second.begin(); it!=second.end(); ++it)
    cout << ' ' << *it;
  cout << '\n';

  return 0;
}

輸出:

first contains:20 25 32
second contains:10 12 75

示例 4

讓我們看一個簡單的例子:

#include <iostream>
#include <string>
#include <set>

using namespace std;

void show(const char *msg, set<int> mp);

int main() {
  set<int> m1, m2;

  m1.insert(100);
  m1.insert(300);
  m1.insert(200);

  // Exchange the contents of m1 and m2.
  cout << "Exchange m1 and m2.\n";
  swap(m1,m2);
  show("Contents of m2:", m2);
  show("Contents of m1:", m1);

 // Clear m1.
  m1.clear();
  if(m1.empty()) cout << "m1 is now empty.";

  return 0;
}

// Display the contents of a set<string, int> by using an iterator.
void show(const char *msg, set<int> mp) {
  set<int>::iterator itr;

  cout << msg << endl;
  for(itr=mp.begin(); itr != mp.end(); ++itr)
    cout << "  " << *itr<< endl;
  cout << endl;
}

輸出:

Exchange m1 and m2.
Contents of m2:
  100
  200
  300

Contents of m1:

m1 is now empty.

在上麵的例子中,set m1 的內容被交換到 set m2 並且交換後 m1 set 已經被清除。






相關用法


注:本文由純淨天空篩選整理自 C++ std swap()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。