7.3 (C++)

7.3 (C++)
请参照map添加两个模版函数map2 。

EXAMPLE OUTPUT

135

501

867

1123

1456

1789

主程序 (不能修改)

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

template <typename A, typename R>
vector<R> map(const vector<A> & x, R (*map_func)(const A &)) {
    vector<R> res;
    for (int i = 0; i < x.size(); ++ i)
        res.push_back(map_func(x[i]));
    return res;
}

#include "source.cpp"

#include <sstream>
// using namespace std;
int to_int(const string & text) {
    stringstream ss(text);
    int val;
    ss >> val;
    return val;
}

vector<string> split(const string & line, 
                    const string & delimiter=" ") {
    vector<string> words;
    int st = 0;
    while (st < line.size()) {
        int end = line.find(delimiter, st);
        if (end == st) st += delimiter.size();
        else {
            if (end == -1) {
                words.push_back(line.substr(st));
                break;
            }
            words.push_back(line.substr(st, end-st));
            st = end + delimiter.size();
        }
    }
    return words;
}

template <typename E>
void print_vector(const vector<E> & c) {
    for (int i = 0; i < c.size(); ++ i) {
        cout << c[i] << endl;
    }
}

int add(const int & x, const int & y) {
    return x + y;
}

int main() {
    string line1 = "123 456 789";
    string line2 = "12 45 78";
    vector<string> words = split(line1);
    vector<int> data1 = map(words, to_int);
    words = split(line2);
    vector<int> data2 = map(words, to_int);
    vector<int> sum1 = map2(data1, data2, add);
    print_vector(sum1);
    vector<int> sum2 = map2(data1, 1000, add);
    print_vector(sum2);
}

我的答案

template <typename A, typename R>
vector<R> map2(const vector<A> & x,const vector<A> & y, R (*map_func)(const A &,const A &)) {
    vector<R> res;
    for (int i = 0; i < x.size(); ++ i)
        res.push_back(map_func(x[i],y[i]));
    return res;
}
template <typename A, typename R>
vector<R> map2(const vector<A> & x,const int & y, R (*map_func)(const A &,const A &)) {
    vector<R> res;
    for (int i = 0; i < x.size(); ++ i)
        res.push_back(map_func(x[i],y));
    return res;
}
上一篇: 7.1 (C++) 下一篇: 7.2 (C++)
支持 makedown语法