原題
http://www.codewars.com/kata/56dbe0e313c2f63be4000b25/train/cpp
題目
Moves in squared strings (I)
This kata is the first of a sequence of four about "Squared Strings".
You are given a string of n lines, each substring being n characters long: For example:
s = "abcd\nefgh\nijkl\nmnop"
We will study some transformations of this square of strings.
Vertical mirror: vert_mirror (or vertMirror or vert-mirror)
vert_mirror(s) => "dcba\nhgfe\nlkji\nponm"
Horizontal mirror: hor_mirror (or horMirror or hor-mirror)
hor_mirror(s) => "mnop\nijkl\nefgh\nabcd"
high-order function oper(fct, s) where
fct is the function of one variable f to apply to the string s (fct will be one of vertMirror, horMirror)
s = "abcd\nefgh\nijkl\nmnop"
oper(vert_mirror, s) => "dcba\nhgfe\nlkji\nponm"
oper(hor_mirror, s) => "mnop\nijkl\nefgh\nabcd"
分析
- 字符串矩陣鏡像非常簡單,主要分為三步止喷,分割->交換位置->合并
-
oper()
主要是把函數(shù)作為參數(shù)波桩。
參考答案
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
string horMirror(const string &str){
// 字符串以回車換行分割成數(shù)組
istringstream iss(str);
vector<string> str_vec;
str_vec.assign(istream_iterator<string>(iss),istream_iterator<string>());
// 交換字符串位置
swap_ranges(begin(str_vec),(str_vec.begin()+str_vec.size()/2),str_vec.rbegin());
// 把字符串?dāng)?shù)組組成字符串
ostringstream oss;
copy(begin(str_vec),end(str_vec),ostream_iterator<string>(oss,"\n"));
string res = oss.str();
res.pop_back(); // 除去最后一個回車菲嘴。
return res;
}
string vertMirror(const string &str){
// 字符串以回車換行分割成數(shù)組
istringstream iss(str);
vector<string> str_vec;
str_vec.assign(istream_iterator<string>(iss),istream_iterator<string>());
// 遍歷字符串
for(auto& s:str_vec){
// 交換字符位置
swap_ranges(begin(s),(s.begin()+s.size()/2),s.rbegin());
}
// 把字符串?dāng)?shù)組組成字符串
ostringstream oss;
copy(begin(str_vec),end(str_vec),ostream_iterator<string>(oss,"\n"));
string res = oss.str();
res.pop_back(); // 除去最后一個回車阀坏。
return res;
}
string oper(string (func)(const string &),const string &s){
return func(s);
}
說明
1.字符串分割成向量的C++慣用法(流默認(rèn)以空格、回車鸡挠、Tab作為分割符)譬嚣。
2.容器范圍數(shù)據(jù)交換swap_range()
。
3.容器元素連接成字符串犀忱。
其它
無