首页 > 文章列表 > C++ 函数有哪些 STL 函数是容器相关的?

C++ 函数有哪些 STL 函数是容器相关的?

容器 STL
328 2025-02-02

C++ STL 中与容器相关的函数:begin() 和 end():获取容器开头和结尾的迭代器,用于遍历容器。rbegin() 和 rend():获取反向迭代器,用于反向遍历容器。empty():检查容器是否为空。size():返回容器中元素的数量。clear():删除容器中的所有元素,使其为空。

C++ 函数有哪些 STL 函数是容器相关的?

C++ STL 中的容器相关函数

STL(标准模板库)提供了广泛的容器类和函数,用于在 C++ 中管理集合。本文将重点介绍与容器相关的最常用函数。

1. begin() 和 end():

这些函数用于获取容器开头和结尾的迭代器。它们广泛用于遍历容器:

#include <vector>

int main() {
  std::vector<int> vec = {1, 2, 3, 4, 5};

  for (auto it = vec.begin(); it != vec.end(); ++it) {
    std::cout << *it << " ";  // 输出:1 2 3 4 5
  }

  return 0;
}

2. rbegin() 和 rend():

这些函数与 begin()end() 类似,但它们用于获取反向迭代器,从而反向遍历容器:

for (auto it = vec.rbegin(); it != vec.rend(); ++it) {
    std::cout << *it << " ";  // 输出:5 4 3 2 1
}

3. empty():

此函数检查容器是否为空(不包含任何元素):

if (vec.empty()) {
    std::cout << "Vector is empty." << std::endl;
}

4. size():

此函数返回容器中元素的数量:

std::cout << "Vector size: " << vec.size() << std::endl;  // 输出:5

5. clear():

此函数删除容器中的所有元素,有效地使其为空:

vec.clear();

实战案例:

以下是一个使用 STL 容器相关函数的实际示例,用于从文件中读取数字并计算它们的总和:

#include <iostream>
#include <fstream>
#include <vector>

int main() {
  std::ifstream infile("numbers.txt");
  if (!infile) {
    std::cerr << "Error opening file." << std::endl;
    return 1;
  }

  std::vector<int> numbers;
  int num;
  while (infile >> num) {
    numbers.push_back(num);
  }

  int sum = 0;
  for (auto it = numbers.begin(); it != numbers.end(); ++it) {
    sum += *it;
  }

  std::cout << "Sum of numbers: " << sum << std::endl;

  return 0;
}