C++笔试常用模板

2018-09-05  本文已影响20人  编程半岛

字符串切分

// istream& getline (istream&  is, string& str, char delim);
// 参数说明:
//          is:需要分割的流
//          str:分割的项
//          delim:分割标识符
vector<string> split(const string s, char delim) {
    stringstream ss(s);                         // 将string转换为流
    string item;                                
    vector<string> elems;                       // 返回值
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

STL中最大堆与最小堆的使用

#include <iostream>
#include <vector>
#include <string>
#include <queue>

using namespace std;

// 最大堆与最小堆测试

struct cmp
{
    bool operator()(int a, int b) {
        return a > b;
    }
};

int main()
{
    priority_queue<int> max_heap;
    priority_queue<int, vector<int>, cmp > min_heap;
    
    for (int i = 0; i < 10; ++i)
    {
        max_heap.push(i);
    }

    cout << "最大堆排序:";
    while (!max_heap.empty())
    {
        cout << max_heap.top() << " ";
        max_heap.pop();
    }
    cout << endl;

    for (int i = 0; i < 10; ++i)
    {
        min_heap.push(i);
    }

    cout << "最小堆排序:";
    while (!min_heap.empty())
    {
        cout << min_heap.top() << " ";
        min_heap.pop();
    }

    cout << endl;
    
    system("pause");
    return 0;
}

生成0~N的随机数

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
    int N = 25;
    srand(time(0)); // 随机数的初始化函数,为随机数播下种子
    int num = rand() % (N + 1);
    cout << num << endl;
    
    system("pause");
    return 0;
}

int转string与string转int

int == > string to_string函数

    // to_string example
    #include <iostream>   // std::cout
    #include <string>     // std::string, std::to_string
     
    int 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;
    }

string ==> int :采用标准库中atoi函数,对于其他类型也都有相应的标准库函数,比如浮点型atof(),long型atol()等等

    string s = "12"; 
    int a = atoi(s.c_str());
上一篇下一篇

猜你喜欢

热点阅读