C++ Primer 5th 第十七章

17.4 编写并测试你自己版本的findbook函数

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <tuple>
#include "Sales_data.h"
using namespace std;
bool compareISBN(const Sales_data&lhs, const Sales_data&rhs) {
    return lhs.isbn() < rhs.isbn();
}
typedef tuple<vector<Sales_data>::size_type, vector<Sales_data>::const_iterator,
    vector<Sales_data>::const_iterator>matches;

//match function
vector<matches> findbook(const vector<vector<Sales_data>> &files,
    const string &book) {
    vector<matches>ret;
    for (auto it = files.cbegin(); it != files.cend(); ++it) {
        auto found = equal_range(it->cbegin(), it->cend(), book, compareISBN);
        if (found.first != found.second) {
            ret.push_back(make_tuple(it - files.cbegin(),
                found.first, found.second));
        }
    }
    return ret;
}

17.5 重写findBook,令其返回一个pair,包含一个索引和一个迭代器pair

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <tuple>
#include "Sales_data.h"
using namespace std;
bool compareISBN(const Sales_data&lhs, const Sales_data&rhs) {
    return lhs.isbn() < rhs.isbn();
}
typedef pair<vector<Sales_data>::size_type,pair<vector<Sales_data>::const_iterator,
    vector<Sales_data>::const_iterator>>matches;

//match function
vector<matches> findbook(const vector<vector<Sales_data>> &files,
    const string &book) {
    vector<matches>ret;
    for (auto it = files.cbegin(); it != files.cend(); ++it) {
        auto found = equal_range(it->cbegin(), it->cend(), book, compareISBN);
        if (found.first != found.second) {
            ret.push_back(make_pair(it - files.cbegin(),found));
        }
    }
    return ret;
}

(转载)17.6 重写findBook,不适用tuple或pair。

template <typename T>    
class matches_result{    
public:    
    make_match(vector<T>::size_type i, vector<T>::const_iterator it1, vector<T>::const_iterator it2) : index(i), first(it1), second(it2){}    
    vector<T>::size_type index;    
    vector<T>::const_iterator first, second;    
};    

matches_result<Sales_data>    
findBook(const vector<vector<Sales_data>> &files, const string &book)    
{    
    matches_result<Sales_data> ret;  // initially empty    
    // for each store find the range of matching books, if any    
    for (auto it = files.cbegin(); it != files.cend(); ++it) {    
        // find the range of Sales_data that have the same ISBN    
        auto found = equal_range(it->cbegin(), it->cend(), book, compareIsbn);    
        if (found.first != found.second)  // this store had sales    
            // remember the index of this store and the matching range     
            ret.make_match(it - files.cbegin(), found.first, found.second);    
    }    
    return ret; // empty if no matches found    
}   

17.2.2

#include <iostream>
#include <algorithm>
#include <bitset>
using namespace std;
template<unsigned N>
bitset<N>initial_bit() {
    bitset<N>x;
    return x;
}
int main() {
    auto vec1 = initial_bit<10>();
    auto vec2 = initial_bit<100>();
    vec1.set(6, 1);
    //cout << vec1 << endl;
    //cout << vec2 << endl;
    unsigned long ff = vec1.to_ulong();//这个地方不是特别确定 不知道他说的整型对象是啥
    cout << ff << endl;
}

17.14(转载)

#include <iostream>
#include <algorithm>
#include <bitset>
#include <regex>
using namespace std;
int main() {
    try {
        regex r("[[:alnum:]+\\.(cpp||cxx||cc)$",regex::icase);
    }
    catch (regex_error e) {
        cout << e.what() << "\ncode: " << e.code() << endl;
    }
    try {
        regex g("[[:alnum:]]+\\.(cpp||cxx||cc)$");
    }
    catch (regex_error f) {
        cout << f.what() << "\ncode: " << f.code() << endl;
    }

}

17.15

#include <iostream>
#include <algorithm>
#include <bitset>
#include <regex>
using namespace std;
int main() {
    regex r("[[:alpha:]]*[^c]ei[[:alpha:]]*");
    string text;
    smatch results;
    while (cin >> text) {
        if (regex_match(text, results, r))cout << "No" << endl;
        else cout << "Ok" << endl;
    }

}

17.16

只有输入的字符串 ei前有字符时会输出no,也就是他只会检测ei之前,若ei符合,就不会检测ei之后了  

17.17

#include <iostream>
#include <algorithm>
#include <bitset>
#include <regex>
using namespace std;
int main() {
    regex r("[[:alpha:]]*[^c]ei[[:alpha:]]*",regex::icase);// ignore the caps
    string text = "receipt freind theif receive";
    smatch results;
    for (sregex_iterator it(text.begin(), text.end(), r), end_it; 
        it != end_it; ++it) {
        cout << it->str() << endl;
    }

}

17.18(转载 侵删)

#include <iostream>    
#include <string>    
#include <regex>    
#include <fstream>    
#include <vector>    
int main(int argc, char **argv)    
{    
    using namespace std;    
    ifstream file(argv[1]);    
    if (!file)    
    {    
        cerr << "open file error!";    
        exit(1);    
    }    
    string p("[^c]ei");    
    p = "[[:alpha:]]*" + p + "[[:alpha:]]*";    
    regex reg(p, regex::icase);    
    string temp, str;    
    while (getline(file, temp))    
        str = str + temp + "\n";    
    vector<string> vec{ "albeit","beige","feint","heir","reign","their",    
        "counterfeit","foreign","inveigh","rein","veil","deign",    
        "forfeit","inveigle","seize","veineiderdown","freight",    
        "leisure","skein","weigheight","heifer","neigh","sleigh",    
        "weighteither","height","neighbour","sleight","weirfeign",    
        "heinous neither surfeit weird" };    
    for (sregex_iterator it(str.begin(), str.end(), reg), end_it; it != end_it; ++it)    
    {    
        if (find(vec.begin(), vec.end(), it->str()) != vec.end())  
            continue;    
        cout << it->str();    
        system("pause");    
        auto pos = it->prefix().length();    
        cout << it->prefix().str().substr(pos > 40 ? pos - 40 : 0) << "[> " << it->str() << "<]" << it->suffix().str().substr(0, 40) << endl;    
    }    

    system("pause");    
    return 0;    
}

17.19

调用str()若不match会返回空string

17.20

#include <iostream>
#include <algorithm>
#include <bitset>
#include <regex>
using namespace std;
bool valid(const smatch& m) {
    if (m[1].matched)
        return m[3].matched && (m[4].matched == false || m[4].str() == " ");
    else
        return !m[3].matched&&m[4].str() == m[6].str();
}
int main() {
    string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
    regex r(phone);
    smatch m;//container
    string s;
    while (getline(cin, s)) {
        for (sregex_iterator it(s.begin(), s.end(), r), end_it;//end iterator
            it != end_it; ++it) {
            if (valid(*it))
                cout << "valid: " << it->str() << endl;
            else
                cout << "not valid: " << it->str() << endl;
        }
    }
}

17.21

#include <iostream>
#include <algorithm>
#include <bitset>
#include <regex>
#include <sstream>
#include <fstream>
#include <vector>
using namespace std;
struct PersonInfo {
    string name;
    vector<string>phone;
};
vector<PersonInfo>people;
bool valid(const smatch& m) {
    if (m[1].matched)
        return m[3].matched && (m[4].matched == false || m[4].str() == " ");
    else
        return !m[3].matched&&m[4].str() == m[6].str();
}
int main() {
    string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
    regex r(phone);
    for (const auto&entry : people) {
        ostringstream formatted, badNums;
        for (const auto &num : entry.phone) {
            for (sregex_iterator it(num.begin(), num.end(), r), end_it; it != end_it;
                ++it) {
                if (!valid(*it)) {
                    badNums << " " << num;
                }
                else {
                    formatted << " " << format(num);//format 函数还没有定义
                }
            }
        }
        //下面省略了
    }
}

17.22

"(\\()?(\\d{3})(\\))?([[:blank:]]*)?(\\d{3})([[:blank:]]*)?(\\d{4})" 

17.23

#include <iostream>
#include <algorithm>
#include <bitset>
#include <regex>
using namespace std;
bool valid(const smatch& m) {
    if (m[2].matched)
        return m[3].matched;
    else
        return 1;
}
int main() {
    string Postal_code = "(\\d{5})([-])?(\\d{4})?";
    regex r(Postal_code);
    smatch m;//container
    string s;
    while (getline(cin, s)) {
        for (sregex_iterator it(s.begin(), s.end(), r), end_it;//end iterator
            it != end_it; ++it) {
            if (valid(*it))
                cout << "valid: " << it->str() << endl;
            else
                cout << "not valid: " << it->str() << endl;
        }
    }
}

17.24

#include <iostream>
#include <algorithm>
#include <bitset>
#include <regex>
using namespace std;
using std::regex_constants::format_no_copy;
int main() {
    string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
    string fmt = "$2.$5.$7";
    regex r(phone);
    string phnmber;
    while (getline(cin, phnmber)) {
        cout << regex_replace(phnmber, r, fmt, format_no_copy) << endl;
    }
}

17.25

#include <iostream>
#include <algorithm>
#include <bitset>
#include <regex>
#include <sstream>
using namespace std;
using std::regex_constants::format_no_copy;
using std::regex_constants::match_prev_avail;
int main() {
    string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
    string fmt = "$2.$5.$7 ";
    regex r(phone);
    string phnmber, finn;
    while (getline(cin, phnmber)) {
        istringstream str(regex_replace(phnmber, r, fmt, format_no_copy));
        str >> finn;
        cout << finn<<endl;
    }
}

17.26

#include <iostream>
#include <algorithm>
#include <bitset>
#include <regex>
#include <sstream>
using namespace std;
using std::regex_constants::format_no_copy;
int main() {
    string phone = "(\\()?(\\d{3})(\\))?([-. ])?(\\d{3})([-. ])?(\\d{4})";
    string fmt = "$2.$5.$7 ";
    regex r(phone);
    string phnmber, finn;
    string num[10];
    int i = 0;
    while (getline(cin, phnmber)) {
        istringstream str(regex_replace(phnmber, r, fmt, format_no_copy));
        while (str >> num[i++]);
        for (int j = 1; j < i - 1; ++j) {
            cout << num[j] << " ";
        }
        cout << endl;
    }
}

17.27

#include <iostream>
#include <algorithm>
#include <bitset>
#include <regex>
using namespace std;
using std::regex_constants::format_no_copy;
int main() {
    string Postal_code = "(\\d{5})([-])?(\\d{4})?";
    regex r(Postal_code);
    string fmt = "$1-$3 ";
    string code;
    while (getline(cin, code)) {
        //cout << code;
        cout << regex_replace(code, r, fmt,format_no_copy) << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/Leslie5205912/article/details/80458580