一些很少用到但是用到时又很抓鸡的代码

来源:互联网 发布:嘟嘟通话录音软件 编辑:程序博客网 时间:2024/04/29 08:23

这里记录一些平时很少用到但是甬道的时候会很抓鸡的代码

1.字符串的旋转

字符串的旋转

对于一个字符串,和字符串中的某一位置,请设计一个算法,将包括i位置在内的左侧部分移动到右边,将右侧部分移动到左边。

给定字符串A和它的长度n以及特定位置p,请返回旋转后的结果。

测试样例:
"ABCDEFGH",8,4
返回:"FGHABCDE"
代码:

class StringRotation {public:    string rotateString(string A, int n, int p) {        return A.substr(p+1,n) + A.substr(0,p+1);    }};

问:漂亮你个毛线,不就是用了一个库函数吗?难道你不会用吗?

答:我还真的不会用。。。。

2.C++ string 类 assign函数的用法

string (1)

string& assign (const string& str);
substring (2)
string& assign (const string& str, size_t subpos, size_t sublen);
c-string (3)
string& assign (const char* s);
buffer (4)
string& assign (const char* s, size_t n);
fill (5)
string& assign (size_t n, char c);
range (6)
template <class InputIterator>   string& assign (InputIterator first, InputIterator last);
我想看这个表格应该就能看懂了


3.unique函数的使用

下面是一段测试代码,我发现我还是喜欢vim的界面

下面是代码的原文

# include <iostream># include <vector># include <cstdlib># include <algorithm>using namespace std;void PrintVector(vector<int>& vct){for (int i=0;i<vct.size();i++) cout << vct[i] << (i==vct.size()-1?'\n':' ');} //#打印vector<int> 的函数 int main() {std::ios::sync_with_stdio(false);cin.tie(0);int i,j;const int n = 15;vector<int> vct(n);for (i=0;i<n;i++) vct[i] = rand()%10;// 对数组进行随机赋值sort(vct.begin(),vct.end());// 使用unique要求数组本身有序PrintVector(vct); // 打印初始序列vct.erase(unique(vct.begin(),vct.end()),vct.end()); // unique 函数会返回第一个无效地址的位置PrintVector(vct); // 打印删除后的序列return 0;}/*输出结果:0 1 2 2 3 3 3 5 5 6 6 7 7 9 90 1 2 3 5 6 7 9*/


3.翻转整数的二进制

发现了一个不错的函数,作用是将整数的二进制表示翻转后的值返回。

int flipNum(int x){    if (x & 1) return x;    int n = 0;    while (x){        n = (n << 1) | (x & 1);        x = x >> 1;    }    return n;}

4.打乱数组的某一段的顺序

// random_shuffle example#include <iostream>     // std::cout#include <algorithm>    // std::random_shuffle#include <vector>       // std::vector#include <ctime>        // std::time#include <cstdlib>      // std::rand, std::srand// random generator function:int myrandom (int i) { return std::rand()%i;}int main () {  std::srand ( unsigned ( std::time(0) ) );  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 9  // using built-in random generator:  std::random_shuffle ( myvector.begin(), myvector.end() );  // using myrandom:  std::random_shuffle ( myvector.begin(), myvector.end(), myrandom);  // 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.计算一个函数的运行时间

# include <iostream># include <time.h>using namespace std;clock_t start, stop;double duration;int main(){std::ios::sync_with_stdio(false);start = clock();/**     *  My Function();**/stop = clock();cout << double(stop - start)/CLOCKS_PER_SEC << endl; /*或者使用CLK_TCK 但我这里CLK_TCK无法使用*/return 0;}


0 0
原创粉丝点击