c++ primer 第十七章习题
练习17.1
tuple<int,int,int> t1{10,20,30};
练习17.2
tuple<string,vector<string>,pair<string,int>> t;
练习17.3 类,有明确的成员名
练习17.8 无法相加因此报错
练习17.9 (a 第五位为1,其它都为0 (b 1010101二进制对应的形式 (c 根据输入而定
练习17.10
int main() {
bitset<32> b1(0x0020212e);
bitset<32> b2;
b2.set(1,1);
b2.set(2,1);
b2.set(3,1);
b2.set(5,1);
b2.set(8,1);
b2.set(13,1);
b2.set(21,1);
cout << b1.to_ulong()<<endl;
cout << b2.to_ulong()<<endl;
return 0;
}
练习17.11 12 13
class test
{
public:
void setResult(int i, bool val) {
b[i] = val;
}
test(int x):b(x) {
}
bool check(int i) {
return b[i];
}
private:
bitset<100> b;
};
练习17.15
int main() {
string pattern("[^c]ei");
pattern = "[[:alpha:]]*"+pattern+"[[:alpha:]]*";
try{
regex r(pattern);
smatch results;
string test_str;
cout << "please input a word: ";
while (cin >> test_str){
if(regex_search(test_str,results,r))
cout << results.str() << " violates the rule "<<endl;
else
cout << "it doesn't violate the rule"<<endl;
cout << "please input a word: ";
}
}
catch(regex_error e) {
cout << e.what() << "\ncode: " << e.code() <<endl;
}
return 0;
}
练习17.16 只会输出匹配的部分
练习17.17
int main() {
string pattern("[^c]ei");
pattern = "[[:alpha:]]*"+pattern+"[[:alpha:]]*";
try{
regex r(pattern);
smatch results;
string test_str = "hello albeit freind receipt ";
for(sregex_iterator it(test_str.begin(),test_str.end(),r),end_it; it != end_it; it++) {
cout << it->str()<<endl;
}
}
catch(regex_error e) {
cout << e.what() << "\ncode: " << e.code() <<endl;
}
return 0;
}
练习17.23
int main() {
string pattern("[^c]ei");
pattern = "(\\d{5})([-]?\\d{4})?";
try{
regex r(pattern);
smatch results;
string test_str = "543214321";
for(sregex_iterator it(test_str.begin(),test_str.end(),r),end_it; it != end_it; it++) {
cout << it->str()<<endl;
}
}
catch(regex_error e) {
cout << e.what() << "\ncode: " << e.code() <<endl;
}
return 0;
}
练习17.27
int main() {
string pattern("[^c]ei");
pattern = "(\\d{5})([-])?(\\d{4})?";
try{
regex r(pattern);
smatch results;
string fmt = "$1-$3";
string test_str = "54321-4321";
cout << regex_replace(test_str,r,fmt);
}
catch(regex_error e) {
cout << e.what() << "\ncode: " << e.code() <<endl;
}
return 0;
}
练习17.28
int randomInt() {
static default_random_engine e;
uniform_int_distribution<unsigned> u(0,100);
return u(e);
}
int main() {
for(int i = 0; i < 10; i++)
cout << randomInt()<<endl;
return 0;
}
练习17.29 30
int randomInt(unsigned int s,unsigned beg, unsigned end) {
default_random_engine e(s);
uniform_int_distribution<unsigned> u(beg,end);
u(e); //此处不先调用一次的话返回值都是一样的,不知为何
return u(e);
}
int main() {
for(int i = 0; i < 10; i++)
cout << randomInt(i+1,10,100)<<endl;
return 0;
}
练习17.31 每一次得到的结果不变
练习17.32 输入时出错