Home > Backend Development > C++ > body text

How to find elements in a C++ STL container?

王林
Release: 2024-06-05 19:44:11
Original
927 people have browsed it

To find elements in a C++ STL container, you can use the following methods: find() function: Find the first element that matches the specified value. find_if() function: Find the first element that meets the specified condition. count() function: Returns the number of elements in the container that are equal to the specified value.

如何查找C++ STL容器中的元素?

How to find elements in a C++ STL container

In C++, STL (Standard Template Library) provides a set of powerful Container class for storing and managing data. Finding elements in a container is one of the common tasks, and STL provides several ways to accomplish this.

find() function

find() The function is used to find the first element that matches the specified value. Valid for all sequential containers (such as vector and list) and associative containers (such as map and set).

#include <vector>

int main() {
  std::vector<int> v = {1, 3, 5, 7, 9};

  // 查找元素 5
  auto it = std::find(v.begin(), v.end(), 5);

  // 如果元素找到,it 将指向该元素
  if (it != v.end()) {
    std::cout << "元素 5 找到" << std::endl;
  } else {
    std::cout << "元素 5 未找到" << std::endl;
  }

  return 0;
}
Copy after login

find_if() function

find_if() The function is used to find the first element that meets the specified condition. It accepts a predicate (a function that returns a boolean value) as an argument.

#include <vector>

int main() {
  std::vector<int> v = {1, 3, 5, 7, 9};

  // 查找第一个大于 5 的元素
  auto it = std::find_if(v.begin(), v.end(), [](int x) { return x > 5; });

  // 如果元素找到,it 将指向该元素
  if (it != v.end()) {
    std::cout << "第一个大于 5 的元素为 " << *it << std::endl;
  } else {
    std::cout << "没有找到大于 5 的元素" << std::endl;
  }

  return 0;
}
Copy after login

count() function

count() The function returns the number of elements in the container that are equal to the specified value.

#include <vector>

int main() {
  std::vector<int> v = {1, 1, 3, 5, 1, 7, 9};

  // 计算元素 1 出现的次数
  int count = std::count(v.begin(), v.end(), 1);

  std::cout << "元素 1 出现的次数为 " << count << std::endl;

  return 0;
}
Copy after login

The above is the detailed content of How to find elements in a C++ STL container?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!