我有一个长度为 500 万的字符串,可以分成所需长度的子字符串(5 或 10 或...)。并将片段存储到 vector 中。我这样做的方式似乎需要很长时间。寻找一种超快速的方法。
示例代码我是如何做到的。 Test here
// Example program
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> splits;
std::string text = "ABCDBCDAACBDAADCADACBBCDACDADBCAACDBCADACD";
for(int i = 0; i < text.length() ; i+= 5)
{
splits.push_back(text.substr (i, 5));
std::cout << "splits: " << text.substr(i, 5) << std::endl;
}
}
最佳答案
这样会快一点。
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> splits;
std::string text = "ABCDBCDAACBDAADCADACBBCDACDADBCAACDBCADACD";
// Start timing
splits.reserve( (text.length()+5-1)/5 );
const auto end = text.begin() +(text.length()/5)*5;
auto it = text.begin();
for(; it < end; it += 5)
{
splits.emplace_back(it, it+5);
}
if (it != text.end())
{
splits.emplace_back(it,text.end());
}
//end timing
for (const auto& str : splits)
{
std::cout << "splits: " << str << std::endl;
}
}
它不是使用 substr
创建一个新字符串,然后将该字符串复制到 vector 中,而是直接创建该字符串。为了尽可能简单,主循环只创建完整长度的字符串,然后单独处理末尾的任何部分字符串。
它还会从计时循环中删除打印(如果您真的这样做,请不要这样做!IO 很慢)。
在创建字符串之前,最终在 vector 中保留了足够的空间(尽管我注意到您在评论中说您正在这样做)。
话虽如此,您不使用 std::string 而只是在 text
中使用偏移量 + 长度的替代表示形式仍然会快得多。
鉴于您知道您只持有短字符串,这是一个单独的类,它有一个固定长度的数组(15 个字节?)加上一个长度(1 个字节)。可能是一个中间步骤。 glibc 没有短字符串优化,因此分配 2000 万 block 内存不会那么快。
最后的想法:你启用了优化,不是吗?这将带来巨大的不同。
关于c++ - 在 C++ 中拆分字符串的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37154158/