最直接的方式是使用 std::find,需包含 并用 std::begin/std::end 传入范围,返回迭代器需与结束迭代器比较;手写循环更灵活可控;有序数组可用 std::binary_search 提升效率但要求已排序。

用 std::find 最直接,但得记得加头文件和命名空间
标准库的 std::find 是最常用也最安全的方式,它不依赖数组是否有序,适用于所有随机访问容器(包括原生数组)。但新手常漏掉两件事:#include <algorithm></algorithm> 和作用域限定。
- 对原生数组使用时,必须传入指针范围:起始地址和结束地址(注意是尾后指针,不是最后一个元素)
- 返回值是迭代器,查不到时等于结束迭代器,不能直接当
bool用 - 如果数组是
int arr[5],std::end(arr)比手写arr + 5更不易出错
#include <algorithm>
#include <iostream><p>int main() {
int arr[] = {1, 3, 5, 7, 9};
auto it = std::find(std::begin(arr), std::end(arr), 5);
if (it != std::end(arr)) {
std::cout </p>
<h3>手写循环更可控,适合嵌入式或禁用 STL 的场景</h3>
<p>当项目禁止 STL、或需要提前退出、或要同时记录位置/次数时,裸循环反而更清晰。关键点在于边界判断别越界,尤其用 <code>sizeof</code> 算长度时容易误算指针大小。</p>
<ul>
<li>对栈上数组,用 <code>sizeof(arr)/sizeof(arr[0])</code> 是安全的;但传入函数后退化为指针,这招就失效</li>
<li>推荐封装成模板函数,避免重复写循环逻辑</li>
<li>若需查找多个匹配项,循环里直接 <code>break</code> 或收集索引比 <code>std::find</code> 多次调用更高效</li>
</ul>
<pre class="brush:php;toolbar:false;">template<typename t size_t n>
bool contains(const T (&arr)[N], const T& value) {
for (size_t i = 0; i <h3>数组有序时,<code>std::binary_search</code> 效率更高但有前提</h3>
<p>如果确定数组已升序排列,<code>std::binary_search</code> 时间复杂度是 O(log n),比线性查找快得多。但它只返回 <code>bool</code>,不提供位置信息,且对无序数据结果未定义——不是慢,是错。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2823" title="C++14"><img
src="https://img.php.cn/upload/manual/001/431/639/6ac8b33c327c4749.png" alt="C++14" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="overflowclass">C++14</a>
<p class="overflowclass">C++14 对 C++11 的修正与增强版本,适合旧系统维护和较老工具链兼容。</p>
</div>
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<ul>
<li>必须确保数组已排序,且排序依据和查找逻辑一致(比如按 <code>int</code> 值排,就别拿 <code>float</code> 查)</li>
<li>同样需要 <code><algorithm></algorithm></code>,参数范围语义和 <code>std::find</code> 一致</li>
<li>若还需知道下标,得用 <code>std::lower_bound</code> 配合判断,而不是硬套 <code>binary_search</code>
</li>
</ul>
<pre class="brush:php;toolbar:false;">int sorted_arr[] = {1, 2, 4, 6, 8, 10};
bool found = std::binary_search(std::begin(sorted_arr), std::end(sorted_arr), 6); // true
常见错误:把指针当数组、忽略 const 正确性、比较类型不匹配
很多崩溃或查不到,其实和算法无关,而是底层访问出了问题。比如把动态分配的指针传给依赖 std::begin 的模板,或者用 == 比较浮点数。
-
int* p = new int[5]{...}; std::find(p, p+5, x)可行,但std::begin(p)编译不过——std::begin只接受数组类型,不接受指针 - 查找
const数组时,std::find返回const_iterator,赋给非 const 迭代器会编译失败 - 查
double值时别直接用==,应改用std::abs(a - b)
真正麻烦的从来不是“怎么写”,而是“在哪调用”和“数据状态是否符合预期”。比如函数接口暴露的是 int* 和 size_t len,你就没法用 std::begin,只能老老实实传指针范围——这时候手写循环反而最省心。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










