【发布时间】:2016-04-17 05:45:40
【问题描述】:
我想创建一个函数来将字符串拆分为等长的子字符串n 一个字符一个字符并返回一个字符向量。
例如F('atgctgttg',n=5) 应该返回
'atgct','tgctg','gctgt','ctgtt','tgttg'
我尝试了两种不同的功能:
// [[Rcpp::export]]
CharacterVector f( const std::string str, const int n ) {
int lim = str.length() - n + 1;
CharacterVector result( lim );
for ( int j = 0; j < lim; j++ )
{
result[j] = str.substr( j, n );
}
return result;
}
和
// [[Rcpp::export]]
CharacterVector f1( const std::string str, const int n ) {
const int lim = str.length();
const int n1 = n - 1;
CharacterVector result( lim - n1 );
int j = 1;
std::string tmp = str.substr( 0, n );
result[0] = tmp;
for ( int i = n; i < lim; i++ )
{
tmp.erase( 0, 1 );
tmp.push_back( str[i] );
result[j] = tmp;
j++;
}
return result;
}
我也尝试过使用迭代器,但它并不比函数 f1 快。
请注意,Rcpp 将输入转换为参考变量。
有没有更快的方法来做到这一点?
【问题讨论】:
-
我目前没有看到。我几乎不敢问,但
f1()真的比f()快吗?那是可怕的代码... -
您没有指定
CharacterVector是什么,并且通过const&传递std::string比仅使用const更有意义。 -
假设
CharacterVector是std::vector的typedef,您可能希望在任何推回之前调用reserve,而不是使用所有空字符串对其进行初始化。 -
@MohamedEzzeddineMacherki:您是否测量
f1更快,或者您是否假设?你有没有测量过你在这里有一个性能问题(我觉得很难相信)?您是否尝试过const std::string & str而不是const std::string str,这可能比f2中的任何有趣的事情都能为您带来更多的性能提升?而且,AndyG 所说的……