如何通过引用传递子字符串? [英] How can I pass a substring by reference?
问题描述
我递归地调用一个函数,该函数将一个子字符串作为参数传递,该子字符串始终从当前字符串的开头一直到某个位置。如果使用的是C,则可以将指针传递到字符串的第一个位置,然后传递必要的长度。不过,我想使用类 string
达到相同的结果。可能吗?如果我使用 const
,编译器是否足够聪明以自行进行优化?更好的是,有没有一种方法可以自己检查编译器实际上是复制参数还是传递引用?
I call recursively a function passing as argument a substring which always starts from the beginning of the current string up to a position. If I was using C, I could pass the pointer to the first position of the string and then the necessary length. Nevertheless, I would like to achieve the same result using the class string
. Is it possible? If I use const
, is the compiler smart enough to make the optimization on its own? Even better, is there a way to check on my own whether the compiler actually makes a copy of the argument or passes a reference?
我的问题是在编写了以下代码通过了对问题 Alphacode 在问题上的测试,一旦有人使用 atoi
而不是 atof
。
My question was motivated after having written the following code which passes the tests on problem Alphacode on poj, once someone uses atoi
instead of atof
.
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <string>
using namespace std;
map<string, int> cache;
bool valid_character_number(string a) {
return 0 < stoi(a.substr(a.size() - 2, 2)) && stoi(a.substr(a.size() - 2, 2)) <= 26;
}
bool zero_last_digit(string a) {
return a[a.size() - 1] == '0';
}
bool zero_before_last_digit(string a) {
return a[a.size() - 2] == '0';
}
int decodings(string a) {
if (a.size() == 0)
return 1;
if (a.size() == 1) {
if (zero_last_digit(a))
return 0;
else
return 1;
}
if (cache.find(a) != cache.end())
return cache[a];
if (zero_last_digit(a) && valid_character_number(a))
return cache[a] = decodings(a.substr(0, a.size() - 2));
else if (valid_character_number(a) && !zero_before_last_digit(a))
return cache[a] = decodings(a.substr(0, a.size() - 1)) + decodings(a.substr(0, a.size() - 2));
else
return cache[a] = decodings(a.substr(0, a.size() - 1));
}
int main() {
string input;
while (true) {
cin >> input;
if (input.size() == 1 && stoi(input) == 0)
return 0;
cout << decodings(input) << endl;
}
return 0;
}
推荐答案
您不能使用 std :: string
为此,但是您可以轻松地创建自己的类,该类将一对迭代器(开始和结束)保存到另一个字符串或C样式的char *中。和大小。使用C ++ 11(因为已经对其进行了标记),您甚至应该能够使用用户定义的文字语法来创建新类型的字符串。
You cannot use std::string
for this purpose, but you can easily make a class of your own that holds a pair of iterators (begin and end) into another string, or a C-style char* and size. With C++11 (since you tagged it), you should even be able to make a User Defined Literal syntax for creating strings of your new type.
这篇关于如何通过引用传递子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!