首頁  >  文章  >  後端開發  >  如何使用 C++ STL 擴充 C++ 語言的功能?

如何使用 C++ STL 擴充 C++ 語言的功能?

WBOY
WBOY原創
2024-06-04 18:31:02823瀏覽

C++ STL 為 C++ 提供容器、演算法和函數,增強其功能:容器:儲存資料的對象,包括順序容器和關聯容器。演算法:操作資料的函數,包括排序、搜尋和其他演算法。函數:其他有用的函數,如數學、字元操作和隨機函數。

如何使用 C++ STL 扩展 C++ 语言的功能?

如何使用C++ STL 擴充C++ 語言的功能

C++ 標準範本庫(STL) 是一個強大的函式庫,可為C++ 語言提供廣泛的容器、演算法和函數。它使開發人員能夠以乾淨且有效率的方式編寫程式碼。

容器

容器是儲存資料的物件。 STL 提供了以下容器:

  • 順序容器: vector、list、deque
  • 關聯容器: map、set、unordered_map、 unordered_set

演算法

演算法是對資料進行操作的函數。 STL 提供了以下演算法:

  • 排序演算法: sort、stable_sort、partial_sort
  • 搜尋演算法: find、binary_search、lower_bound、 upper_bound
  • 其他演算法: min、max、fill、copy

函數

STL 還提供了許多其他有用的函數,例如:

  • 數學函數: sqrt、pow、abs
  • 字元操作函數: isalpha、isdigit、toupper
  • 隨機函數: rand、srand

#實戰案例

使用vector 儲存整數列表

#include <iostream>
#include <vector>

int main() {
  // 创建一个 vector
  std::vector<int> numbers = {1, 2, 3, 4, 5};

  // 打印 vector 中的元素
  for (auto n : numbers) {
    std::cout << n << " ";
  }
  std::cout << std::endl;

  // 使用 STL 函数对 vector 进行排序
  std::sort(numbers.begin(), numbers.end());

  // 打印排序后的 vector
  for (auto n : numbers) {
    std::cout << n << " ";
  }
  std::cout << std::endl;

  return 0;
}

######################################################## #使用map 儲存單字的計數######
#include <iostream>
#include <map>

int main() {
  // 创建一个 map
  std::map<std::string, int> wordCounts;

  // 往 map 中添加元素
  wordCounts["hello"]++;
  wordCounts["world"]++;
  wordCounts["this"]++;

  // 打印 map 中的元素
  for (auto pair : wordCounts) {
    std::cout << pair.first << " appears " << pair.second << " times" << std::endl;
  }

  return 0;
}

以上是如何使用 C++ STL 擴充 C++ 語言的功能?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn