您的位置:首页 > 编程语言 > C语言/C++

c++11 学习及测试(emplace_back实现方式 数学分布 正则表达式)

2016-03-31 10:42 477 查看
可变长度参数列表,参数原始类型转发(emplace_back实现方式)

#include <iostream>
#include <utility>
#include <string>
#include <vector>
using namespace std;

template<typename T, typename ... Args>
T make(T, Args&& ... rest) { //模版参数列表,右值引用调用构造函数
cout << sizeof...(rest) << endl;
return T(std::forward<Args>(rest) ... ); //按原始类型转发扩展参数,emplace函数的事项方式
}

int main(int argc, char* argv[]) {
string x;
string s = make(x, 10, 'c');
cout << s << endl;

vector<string> v;
v.emplace_back(10, 'c');
cout << v[0] << endl;
cout << "Hello world!" << endl;

return 0;
}按分布采样
#include <iostream>
#include <random>
using namespace std;

int main(int argc, char* argv[]) {
default_random_engine e(time(0));
for(int i =0; i < 10; ++i) {
cout << e() << endl;
}
uniform_real_distribution<> u(0, 1);
for(int i = 0; i < 10; ++i) {
cout << u(e) << endl;
}

normal_distribution<> n(4, 1.5); //均值 标准差
for(int i = 0; i < 10; ++i) {
cout << n(e) << endl;
}
cout << "Hello world!" << endl;

return 0;
}
正则表达式类
#include <iostream>
#include <regex>
using namespace std;

int main(int argc, char* argv[]) {
regex r("[[:alnum:]]+\\.(cpp|cxx|cc)$", regex::icase);
smatch results;
string file;
// regex_search("a.cc", results, r); // 编译错误,char* 对应cmatch, string 对应smatch
cmatch res;
regex_search("a.cc", res, r);
while(cin >> file) {
if(regex_search(file, results, r)) {
cout << results.str() << endl;
} else {
cout << "error file name" << endl;
}
}
return 0;
}正则表达式子匹配,迭代器
#include <iostream>
#include <regex>
using namespace std;

int main(int argc, char* argv[]) {
string pattern("([^c]ei)");
pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
string file = "you are my freiNd, theif";
regex r(pattern, regex::icase);
for(sregex_iterator it(file.begin(), file.end(), r), end_it; it != end_it; ++it) {
cout << it->str() << endl;
cout << it->size() << endl;
cout << it->prefix() << endl;
cout << it->suffix() << endl;
cout << it->length(1) << endl;
cout << it->str(1) << endl;
if((*it)[0].matched) {
for(auto jt = (*it)[0].first; jt != (*it)[0].second; ++jt) {
cout << "[" << *jt << "]" << endl;
}
}
}

string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
regex p(phone);
string fmt = "$2.$5.$7";
string s = "";
s = s + "morgan (201) 555-2365 123-345-1234\n" +
"drew (123)123.1234\n" +
"lee (789) 999-0987 1234567890 900.000.0000";
cout << regex_replace(s, p, fmt) << endl;

cout << s << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: