美文网首页
C++常用代码

C++常用代码

作者: 林逸凡_lyf | 来源:发表于2018-08-11 14:41 被阅读0次

读入多行内容

vector<int> scores;

while(1) {
    string line;
    getline(cin, line); //获取整行到string
    if (line.empty()) { //如果没有输入,跳出循环
        break;
    }
    istringstream iss(line); //将string转为stream
    int d = 0;
    while (iss >> d) { //从stringstream中获取内容
        scores.push_back(d);
    }
}

读取8进制和16进制数

cin >> oct >> i; #输入为八进制数
cin >> hex >> j; #输入为十六进制数
cin >> k; #输入仍为十六进制数, 在cin或cout中指明数制后,该数制将一直有效,直到重新指明使用其他数制。
cin >> dec >> l; #输入为十进制数
cout << hex << j; #输出16进制
cout << j; #输出十进制
#istringstream 同理

字符串分割

std::vector<std::string> split(std::string str,std::string pattern)
{
    std::string::size_type pos;
    std::vector<std::string> result;
    str+=pattern; //扩展字符串以方便操作
    int size=str.size();

    for(int i=0; i<size; i++) {
        pos=str.find(pattern,i); //找到分隔符位置
        if(pos<size) {
            std::string s=str.substr(i,pos-i); //截取到分隔符
            result.push_back(s);
            i = pos+pattern.size()-1;
        }
    }
    return result;
}

string path = "User\lyfne\Documents\C++\hello.cpp";
string filename = path.substr(path.rfind('\\')+1); //取最后一个分割符后的字符, hello.cpp
string rootFolder = path.substr(0, path.find('\\')); //取第一个分隔符前面的字符, User

对map按value排序

typedef pair<string, int> PAIR;
struct CmpByValue {
    bool operator()(const PAIR& lhs, const PAIR& rhs) {
        return lhs.second < rhs.second;
    }
};
int main() {
    //...
    sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());
    //...
}

sort函数的比较函数

bool compare(const pair<string, int>& p1, const pair<string, int>& p2) {
    return p1.second > p2.second;
}//如果在类内,函数前面需要加static
stable_sort(pairs.begin(), pairs.end(), compare);

string转16进制数

string string_to_hex(const string& str) //transfer string to hex-string
{
    string result="0x";
    string tmp;
    stringstream ss;
    for(int i=0;i<str.size();i++)
    {
        ss<<hex<<int(str[i])<<endl;
        ss>>tmp;
        result+=tmp;
    }
    return result;
}
long long string_to_bit(const string& str)//transfer hex-string to bit
{
    long long result=strtoll(str.c_str(), NULL, 16);//第三个参数base为合法字符范围,base=2,为0、1,base=16,合法字符则为0-F,开头的0x自动忽略
    return result;
}

打印指针地址

int i = 10;
int* ptr = &i;
printf("naive memory alloc: %p\n", ptr);

条件编译

#define FLAG 1
#if FLAG
    // code
#else
    // code
#endif

相关文章

网友评论

      本文标题:C++常用代码

      本文链接:https://www.haomeiwen.com/subject/hnldbftx.html