当前位置: 首页 > news >正文

C++ 算法题常用函数大全

目录

  • 1. 类型转换函数
    • 1.1 字符串 ↔ 数值
      • 1.1.1 stoi 函数
      • 1.1.2 stod 函数
      • 1.1.3 to_string 函数
    • 1.2 字符 ↔ 数值
    • 1.3 ASCII 转换
  • 2. 字符串处理函数
  • 3. 通用算法函数
    • 3.1 reverse 函数
    • 3.2 sort 函数
    • 3.3 unique 函数
  • 4. 查找算法函数
    • 4.1 find 函数
    • 4.2 count 函数
  • 5. 数值操作函数
    • 5.1 accumulate 函数
  • 6. 数学函数
  • 7. 自定义比较函数
  • 8. 使用技巧总结

1. 类型转换函数

1.1 字符串 ↔ 数值

1.1.1 stoi 函数

(1)函数原型:

int stoi(const string& str, size_t* idx = 0, int base = 10);

(2)功能:

  • 字符串转整数。

(3)参数解析:

  • str:需要转换的字符串。并且它只会转换数字,当string当中有字符的时候是不会转换的。只会返回数字部分。
  • idx:指向 size_t 类型的对象的指针,其值由函数设置为 str 中数值后下一个字符的位置。此参数也可以是 null 指针,在这种情况下,不使用它。
  • base:

(4)案例:

// stoi example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoiint main ()
{std::string str_dec = "2001, A Space Odyssey";std::string str_hex = "40c3";std::string str_bin = "-10010110001";std::string str_auto = "0x7f";std::string::size_type sz;   // alias of size_tint i_dec = std::stoi (str_dec,&sz);int i_hex = std::stoi (str_hex,nullptr,16);int i_bin = std::stoi (str_bin,nullptr,2);int i_auto = std::stoi (str_auto,nullptr,0);std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";std::cout << str_hex << ": " << i_hex << '\n';std::cout << str_bin << ": " << i_bin << '\n';std::cout << str_auto << ": " << i_auto << '\n';return 0;
}

(5)运行结果:

1.1.2 stod 函数

(1)函数原型:

double stod(const string& str, size_t* idx = 0);

(2)功能:

  • 字符串转浮点数

(3)参数解析:

  • str:需要转换的字符串。
  • idx:如果 idx 不是 null 指针,该函数还会将 idx 的值设置为 str 中数字后的第一个字符的位置。

(4)案例:

// stod example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stodint main ()
{std::string orbits ("365.24 29.53");std::string::size_type sz;     // alias of size_tdouble earth = std::stod(orbits, &sz);double moon = std::stod(orbits.substr(sz));std::cout << "The moon completes " << (earth / moon) << " orbits per Earth year.\n";return 0;
}

(5)运行结果:

1.1.3 to_string 函数

(1)函数原型:

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

(2)功能:

  • 数值转字符串。

(3)参数解析:

  • val:需要转换的数字。

(4)printf 打印的格式表:

(5)案例:

// to_string example
#include <iostream>   // std::cout
#include <string>     // std::string, std::to_stringint main ()
{std::string pi = "pi is " + std::to_string(3.1415926);std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";std::cout << pi << '\n';std::cout << perfect << '\n';return 0;
}

(6)运行结果:

1.2 字符 ↔ 数值

(1)字符与数值相互转换:

// 字符转数字
char c = '7';
int digit = c - '0'; // digit = 7// 数字转字符
int num = 9;
char c = num + '0'; // c = '9'

(2)字符大小写转换 tolower 函数原型:

int tolower(int c);
  • 功能是将大写字符转换成小写。
  • 案例:
/* tolower example */
#include <stdio.h>
#include <ctype.h>
int main ()
{int i=0;char str[]="Test String.\n";char c;while (str[i]){c=str[i];putchar(tolower(c));i++;}return 0;
}
  • 运行结果:

(3)字符大小写转换 toupper 函数原型:

int toupper(int c);
  • 功能是将小写字符转换成大写。
  • 案例:
/* toupper example */
#include <stdio.h>
#include <ctype.h>int main ()
{int i=0;char str[]="Test String.\n";char c;while (str[i]){c=str[i];putchar(toupper(c));i++;}return 0;
}
  • 运行结果:

1.3 ASCII 转换

(1)字符转ASCII:

char ch = 'A';
int ascii = static_cast<int>(ch); // 65

(2)ASCII转字符:

int code = 66;
char ch = static_cast<char>(code); // 'B'

2. 字符串处理函数

(1)substr 函数原型:

string substr(size_t pos = 0, size_t len = npos) const;
  • 功能:切割字符串。
  • 参数解析:
    • pos:切割的起始位置。
    • len:切割的长度。
  • 案例:
string s = "Hello";
string sub = s.substr(1, 3); // "ell"

(2)find函数原型:

size_t find(const string& str, size_t pos = 0) const;
size_t find(const char* s, size_t pos = 0) const;
size_t find(const char* s, size_t pos, size_t n) const;
size_t find(char c, size_t pos = 0) const;
  • 功能:寻找指定的字符串。
  • 案例:
// string::find
#include <iostream>       // std::cout
#include <string>         // std::stringint main ()
{std::string str ("There are two needles in this haystack with needles.");std::string str2 ("needle");// different member versions of find in the same order as above:std::size_t found = str.find(str2);if (found!=std::string::npos)std::cout << "first 'needle' found at: " << found << '\n';found=str.find("needles are small",found+1,6);if (found!=std::string::npos)std::cout << "second 'needle' found at: " << found << '\n';found=str.find("haystack");if (found!=std::string::npos)std::cout << "'haystack' also found at: " << found << '\n';found=str.find('.');if (found!=std::string::npos)std::cout << "Period found at: " << found << '\n';// let's replace the first needle:str.replace(str.find(str2),str2.length(),"preposition");std::cout << str << '\n';return 0;
}
  • 运行结果:

(3)c_str函数原型:

const char* c_str() const;
  • 功能:返回字符串的首地址。
  • 案例:
// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>int main ()
{std::string str ("Please split this sentence into tokens");char * cstr = new char [str.length()+1];std::strcpy (cstr, str.c_str());// cstr now contains a c-string copy of strchar * p = std::strtok (cstr," ");while (p!=0){std::cout << p << '\n';p = std::strtok(NULL," ");}delete[] cstr;return 0;
}
  • 运行结果:

3. 通用算法函数

3.1 reverse 函数

(1)函数原型:

template <class BidirectionalIterator>
void reverse (BidirectionalIterator first, BidirectionalIterator last);

(2)功能:

  • 反转指定区间的数字或者字符串等。

(3)参数解析:

  • first:反转区间的开始位置。
  • last:反转区间的结束位置。区间都是左闭右开。

(4)案例:

// reverse algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::reverse
#include <vector>       // std::vectorint main () 
{std::vector<int> myvector;// set some values:for (int i=1; i<10; ++i) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9std::reverse(myvector.begin(),myvector.end());    // 9 8 7 6 5 4 3 2 1// print out content:std::cout << "myvector contains:";for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)std::cout << ' ' << *it;std::cout << '\n';return 0;
}

(5)运行结果:

3.2 sort 函数

(1)函数原型:

template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

(2)功能:

  • 将指定的区间进行排序。

(3)参数解析:

  • first:排序区间的开始位置。
  • last:排序区间的结束位置。区间都是左闭右开。

(4)案例:

// sort algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::sort
#include <vector>       // std::vectorbool myfunction(int i,int j) { return (i<j); }struct myclass 
{bool operator() (int i,int j) { return (i<j);}
}myobject;int main () 
{int myints[] = {32,71,12,45,26,80,53,33};std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33// using default comparison (operator <):std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33// using function as compstd::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)// using object as compstd::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)// print out content:std::cout << "myvector contains:";for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)std::cout << ' ' << *it;std::cout << '\n';return 0;
}

(5)运行结果:

3.3 unique 函数

(1)函数原型:

template <class ForwardIterator>
ForwardIterator unique (ForwardIterator first, ForwardIterator last);template <class ForwardIterator, class BinaryPredicate>
ForwardIterator unique (ForwardIterator first, ForwardIterator last, BinaryPredicate pred);

(2)功能:

  • 将指定的区间进行去重。

(3)参数解析:

  • first:去重区间的开始位置。
  • last:去重区间的结束位置。区间都是左闭右开。

(4)案例:

// unique algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::unique, std::distance
#include <vector>       // std::vectorbool myfunction (int i, int j) 
{return (i == j);
}int main() 
{int myints[] = {10,20,20,20,30,30,20,20,10};           // 10 20 20 20 30 30 20 20 10std::vector<int> myvector (myints,myints+9);// using default comparison:std::vector<int>::iterator it;it = std::unique (myvector.begin(), myvector.end());   // 10 20 30 20 10 ?  ?  ?  ?//                ^myvector.resize( std::distance(myvector.begin(),it) ); // 10 20 30 20 10// using predicate comparison:std::unique (myvector.begin(), myvector.end(), myfunction);   // (no changes)// print out content:std::cout << "myvector contains:";for (it=myvector.begin(); it!=myvector.end(); ++it)std::cout << ' ' << *it;std::cout << '\n';return 0;
}

(5)运行结果:

4. 查找算法函数

4.1 find 函数

(1)函数原型:

template <class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val);

(2)功能:

  • 指定的区间进行查找指定数值。

(3)参数解析:

  • first:查找区间的开始位置。
  • last:查找区间的结束位置。区间都是左闭右开。
  • val:查找的值。

(4)案例:

// find example
#include <iostream>     // std::cout
#include <algorithm>    // std::find
#include <vector>       // std::vectorint main ()
{// using std::find with array and pointer:int myints[] = { 10, 20, 30, 40 };int * p;p = std::find (myints, myints+4, 30);if(p != myints+4)std::cout << "Element found in myints: " << *p << '\n';elsestd::cout << "Element not found in myints\n";// using std::find with vector and iterator:std::vector<int> myvector (myints,myints+4);std::vector<int>::iterator it;it = find (myvector.begin(), myvector.end(), 30);if(it != myvector.end())std::cout << "Element found in myvector: " << *it << '\n';elsestd::cout << "Element not found in myvector\n";return 0;
}

(5)运行结果:

4.2 count 函数

(1)函数原型:

template <class InputIterator, class T>typename iterator_traits<InputIterator>::difference_typecount (InputIterator first, InputIterator last, const T& val);

(2)功能:

  • 指定的区间进行查找指定数值出现的次数。

(3)参数解析:

  • first:查找区间的开始位置。
  • last:查找区间的结束位置。区间都是左闭右开。
  • val:查找出现次数的值。

(4)案例:

// count algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::count
#include <vector>       // std::vectorint main () 
{// counting elements in array:int myints[] = {10,20,30,30,20,10,10,20};   // 8 elementsint mycount = std::count (myints, myints+8, 10);std::cout << "10 appears " << mycount << " times.\n";// counting elements in container:std::vector<int> myvector (myints, myints+8);mycount = std::count (myvector.begin(), myvector.end(), 20);std::cout << "20 appears " << mycount  << " times.\n";return 0;
}

(5)运行结果:

5. 数值操作函数

5.1 accumulate 函数

(1)函数原型:

template <class InputIterator, class T>T accumulate (InputIterator first, InputIterator last, T init);template <class InputIterator, class T, class BinaryOperation>T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);

(2)功能:

  • 指定的区间进行求和。

(3)参数解析:

  • first:求和区间的开始位置。
  • last:求和区间的结束位置。区间都是左闭右开。
  • init:初始值。
  • op:可选,二元操作函数(默认为加法)。

(4)案例:

// accumulate example
#include <iostream>     // std::cout
#include <functional>   // std::minus
#include <numeric>      // std::accumulateint myfunction (int x, int y) { return x + 2 * y; }
struct myclass 
{int operator()(int x, int y) { return x + 3 * y; }
}myobject;int main () 
{int init = 100;int numbers[] = {10,20,30};std::cout << "using default accumulate: ";std::cout << std::accumulate(numbers,numbers+3,init);std::cout << '\n';std::cout << "using functional's minus: ";std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());std::cout << '\n';std::cout << "using custom function: ";std::cout << std::accumulate (numbers, numbers+3, init, myfunction);std::cout << '\n';std::cout << "using custom object: ";std::cout << std::accumulate (numbers, numbers+3, init, myobject);std::cout << '\n';return 0;
}

(5)运行结果:

6. 数学函数

(1)绝对值:

int abs(int n); // |-5| = 5
double fabs(double x); // |-3.14| = 3.14

(2)幂运算:

double pow(double base, double exp); // 2^3 = 8

(3)平方根:

double sqrt(double x); // √16 = 4.0

(4)取整:

double ceil(double x); // ceil(3.2) = 4.0
double floor(double x); // floor(3.8) = 3.0
double round(double x); // round(3.5) = 4.0
int min_val = min({a, b, c}); // min(3,1,4)=1

(5)最值:

int max_val = max(a, b); // max(3,5)=5
int min_val = min({a, b, c}); // min(3,1,4)=1

7. 自定义比较函数

(1)自定义排序:

sort(intervals.begin(), intervals.end(), [](const auto& a, const auto& b) 
{return a[1] < b[1]; // 按区间终点排序(升序)
});

(2)优先队列自定义排序:

auto cmp = [](int a, int b) { return a > b; }; // 小顶堆
priority_queue<int, vector<int>, decltype(cmp)> pq(cmp);

8. 使用技巧总结

(1)总结:

  1. 字符串处理:优先使用 std::string 成员函数和 算法
  2. 数值转换:使用 stoi/stod 系列函数替代 C 风格的 atoi/atof
  3. 容器操作:善用 STL 算法避免手写循环(如 accumulate, count_if)
  4. 性能优化:使用 reserve() 预分配内存减少动态扩容开销
  5. 自定义排序:Lambda 表达式是编写简洁比较逻辑的最佳选择

(2)重要提示:使用这些函数时注意包含对应头文件:

#include <algorithm> // sort, reverse, etc.
#include <cctype>    // tolower, toupper
#include <cmath>     // abs, pow, sqrt
#include <numeric>   // accumulate
#include <string>    // string functions
#include <vector>    // vector
#include <sstream>   // stringstream

(3)以上是本人在写算法题目的时候碰到的一些常用的算法,如果后续还遇到什么经常用到算法会进行补充,读友们也可以在评论区和我说一下经常用而没有补充的函数。

http://www.dtcms.com/a/276576.html

相关文章:

  • 独立开发第二周:构建、执行、规划
  • 数智管理学(三十二)
  • ATE-市场现状及趋势
  • AI:机器人行业发展现状
  • 用 Jpom 10 分钟搭好一套轻量级 CICD + 运维平台
  • 傅里叶方法求解偏微分方程2
  • 【C/C++】迈出编译第一步——预处理
  • 并查集理论以及实现
  • QILSTE/旗光 H6-108QHR
  • SSM项目上传文件的方式及代码
  • Java使用Langchai4j接入AI大模型的简单使用(二)
  • 线程同步:互斥锁与条件变量实战指南
  • 猿人学js逆向比赛第一届第二十题
  • 关于赛灵思的petalinux zynqmp.dtsi文件的理解
  • 二叉树算法进阶
  • 《Spring 中上下文传递的那些事儿》Part 8:构建统一上下文框架设计与实现(实战篇)
  • 深入理解设计模式之工厂模式:创建对象的艺术
  • Pandas 模块之数据的读取
  • 暑期前端训练day6
  • 【人工智能99问】开篇!
  • 【leetcode】1757. 可回收且低脂的产品
  • FastAdmin项目开发三
  • Python数据容器-集合set
  • 什么是 Bootloader?怎么把它移植到 STM32 上?
  • 关于两种网络攻击方式XSS和CSRF
  • 车载操作系统 --- Linux实时化与硬实时RTOS综述
  • 格密码--数学基础--06对偶空间与对偶格
  • 建造者模式(Builder)
  • Python 实战:构建可扩展的命令行插件引擎
  • Java 方法重载与构造器