stringstream类知识点:
<sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。
1.stringstream::str(); returns a string object with a copy of the current contents of the stream.
2.stringstream::str (const string& s); sets s as the contents of the stream, discarding any previous contents.
3.stringstream清空,stringstream s; s.str("");
4.实现任意类型的转换
template<typename out_type, typename in_value>
out_type convert(const in_value & t){
stringstream stream;
stream<<t;//向流中传值
out_type result;//这里存储转换结果
stream>>result;//向result中写入值
return result;
}
int main(){
string s = "1 23 # 4";
stringstream ss;
ss<<s;
while(ss>>s){
cout<<s<<endl;
int val = convert<int>(s); //转换s为int型。
cout<<val<<endl;
}
return 0;
}
输出:1 1 23 23 # 0 4 4
上述知识点参考的博客忘记了。
substr函数的用法:
0. 用途:一种构造string的方法
1. 形式:s.substr(pos, n)
2. 解释:返回一个string,包含s中从pos开始的n个字符的拷贝(pos的默认值是0,n的默认值是s.size() - pos,即不加参数会默认拷贝整个s)
3. 补充:若pos的值超过了string的大小,则substr函数会抛出一个out_of_range异常;若pos+n的值超过了string的大小,则substr会调整n的值,只拷贝到string的末尾
lintcode第七题答案如下:
class Solution {
public:
/**
* This method will be invoked first, you should design your own algorithm
* to serialize a binary tree which denote by a root node to a string which
* can be easily deserialized by your own "deserialize" method later.
*/
string serialize(TreeNode * root) {
// write your code here
string str;
if (root == NULL)
{
str += "# ";
}
else
{
stringstream ss;
ss << root->val; //向ss中传值
str += ss.str();
str += " ";
str += serialize(root->left);
str += serialize(root->right);
}
return str;
}
/**
* This method will be invoked second, the argument data is what exactly
* you serialized at method "serialize", that means the data is not given by
* system, it's given by your own serialize method. So the format of data is
* designed by yourself, and deserialize it here as you serialize it in
* "serialize" method.
*/
TreeNode * deserialize(string &data) {
// write your code here
if (data.length() == 0)
{
return NULL;
}
else if (data[0] == '#')
{
data = data.substr(2);
return NULL;
}
else
{
int temp;
int counter = 1;
while (data[counter] != ' ')
{
counter++;
}
string temp_str = data.substr(0, counter);
stringstream ss(temp_str);
ss >> temp; //向temp中写入值
TreeNode* wow = new TreeNode(temp);
data = data.substr(counter + 1);
wow->left = deserialize(data);
wow->right = deserialize(data);
return wow;
}
}
};