stoi - 问题与设计 [英] stoi - issue with design
问题描述
我在我的讯息中提出一个问题,代表 boost :: lexical_cast
,在许多回复中,我有一个建议 stoi
作为可行的替代方法。
我决定测试它,令我惊讶的是,这个函数的第二个参数(参数描述大小)是一个指向 size_t
类型的指针,而不是实际 size_t
类型。是否有任何逻辑解释,以什么方式更好地有一个指向实际对象而不是对象本身(只是在这种特殊情况下,当大小,我不会本能地分配大小与指针)?
链接到stoi doc: http://msdn.microsoft.com/zh-TW/library/ee404860.aspx
是一种具有可选参数的方法。基本上,如果你有兴趣知道哪个是未转换为数字的第一个字符。如果你对这个结果不感兴趣,你可以传入nullptr。
§21.5[string.conversions] / 1 [... ]如果函数不抛出异常并且idx!= 0,函数将在* idx中存储str的第一个未转换元素的索引。
这是用于:
int main(){
std :: string two {2及以上内容};
//我不在意,只是想要一个数字:
int i = std :: stoi(two,0,10); // base = 0
std :: size_t first_not_converted;
int i = std :: stoi(two,& first_not_converted,10);
std :: cout<< 未转换的字符串是:< two.substr(first_not_converted)<< std :: endl;
}
使用指针可以使参数真正可选,如果它是一个out参数,但需要使用引用,但这将需要用户代码创建变量始终,无论他们是否对值感兴趣,所以它不会真的是可选的。 / p>
I've asked in one of my posts a question about alternative to boost::lexical_cast
and amongst many replies I've got one suggestion stoi
as a viable alternative.
I've decided to test it and to my surprise as a second argument to this function (argument describing size) is a pointer to size_t
type, not actual size_t
type. Is there any logical explanation for that and in what way it is better to have a pointer to actual object than object itself (just in this particular case when size is concerned and I wouldn't instinctively assign size with pointer)?
Link to stoi doc: http://msdn.microsoft.com/en-us/library/ee404860.aspx
That is a way of having optional arguments. Basically, if you are interested in knowing which is the first character that was not converted into the number. If you are not really interested in that result, you can pass nullptr.
§21.5 [string.conversions]/1 [...] If the function does not throw an exception and idx != 0, the function stores in *idx the index of the first unconverted element of str.
This is meant to be used as:
int main() {
std::string two{"2 and more contents"};
// I don't care, just want a number:
int i = std::stoi( two, 0, 10 ); // base = 0
std::size_t first_not_converted;
int i = std::stoi( two, &first_not_converted, 10 );
std::cout << "Unconverted string is: " << two.substr( first_not_converted ) << std::endl;
}
By using a pointer you can make the argument really optional, if it was an out parameter, but required a reference would be used, but that would require user code to create the variable always regardless of whether they are interested in the value or not, so it would not be really optional.
这篇关于stoi - 问题与设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!