在 C++ 中的字符串开头插入字符的最快方法?
所以在Leetcode上做题的时候我就遇到了这个问题。要正常生成字符串,我可以使用 str.push_back('a')。但如果我想向后生成字符串,我将使用相同的方法并在末尾反转字符串。使用str.insert()导致Time Limit Exceeded and str='a'+str;正如预期的那样,会导致内存超出限制。想知道是否有一种简单的方法可以在 C++ 中的字符串开头插入字符
So while solving problems on Leetcode I came across this problem. To generate a string normally, I could just use str.push_back('a'). But if I want to generate the string backwards I would use this same method and reverse the string at the end. Using str.insert() resulted in Time Limit Exceeded and str='a'+str; would as expected result in Memory Limit Exceeded. Wanted to know if there was an easy way to insert a character at the beginning of the string in C++
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已经通过说反转回答了自己的问题。只需使用 += 运算符追加然后反转即可。
另一种方法是,首先将元素压入堆栈,然后弹出它们以填充字符串。
如果仍然很慢,则将输出分成小段,并管道化反转+附加部分以使用多个线程隐藏延迟。当一个线程反转一个段时,另一个线程可以创建另一个段。然后连接所有线程并连接它们的输出段以使单个字符数组转换为字符串。如果每个段都是L1缓存的大小,那么反转应该很快。
如果您不能使用线程,那么您仍然可以在 sse/avx 寄存器内进行反转,它们具有随机播放命令,可以帮助您使用指令级并行性来隐藏延迟,除非它们比 L1 访问慢。
You already answered your own question by saying reversing. Just use += operator to append and then reverse.
As another way, first push elements into a stack then pop them to fill string.
If it is still slow, then divide the output into small segments and pipeline the reversing + appending parts to hide latency using multiple threads. While one thread is reversing a segment, another thread can create another segment. Then you join all threads and join their output segments to make single array of chars to be converted to string. If each segment is size of L1 cache, then the reversing should be fast.
If you can't use threads, then you can still do the reversing inside sse/avx registers, they have shuffle commands that can help you use the instruction level parallelism to hide the latency, unless they are slower than L1 access.