简体   繁体   English

如何将char数组/字符串复制可变次数C ++

[英]How to copy a char array / String a variable number of times C++

Question: 题:

in C++ : Given the std::string s = "copyme" how can I make a string b which is "copymecopymecopyme" or any generalized s + s + ... n times? 在C ++中:给定std :: string s =“ copyme”,我怎样才能使字符串b为“ copymecopymecopyme”或任何广义的s + s + ... n次?


possible solutions 可能的解决方案

A possible solution would be a method/macro that does a for loop, but that would be horribly inefficient. 可能的解决方案是执行for循环的方法/宏,但效率极低。

What is an efficient method of doing this string copy operation, eg as the previous author says in the style of 'string'*n in python or ruby. 什么是执行此字符串复制操作的有效方法,例如,正如前一位作者在python或ruby中以'string'* n的样式所说的那样。

a relatively efficient loop would be allocating strlen*n and then copying the chars over multiple times rather than for(...) {str+=copy_this_string;} which does multiple copies and allocates. 一个相对有效的循环是分配strlen * n,然后多次复制字符,而不是进行多次复制和分配的for(...){str + = copy_this_string;}。

another solution is using a stringbuffer. 另一个解决方案是使用字符串缓冲区。


SO clarifications SO澄清

key: without using a macro. 关键: 使用宏。 clarification: the 'char array' in the question is because in the original question, due to a single char in the string, all answers ignored the copying of a general stream and focused on using '.' 澄清:问题中的“字符数组”是因为在原始问题中,由于字符串中只有一个字符,所有答案都忽略了通用流的复制,而专注于使用“。” since it had easily accessible methods such as the stream constructor. 因为它具有易于访问的方法,例如流构造器。

"Duplicate" : How to repeat a string a variable number of times in C++? “ Duplicate”: 如何在C ++中将字符串重复可变的次数? Except most the answers all used methods that only had a char repeated, eg the String Constructor and insert methods, which did not answer the original question and were unhelpful when I then looked for an efficient method. 除了大多数答案外,所有使用过的方法都只重复了一个char,例如String Constructor和insert方法,它们没有回答原始问题,并且在我寻找有效方法时无济于事。

If you're worried about the string '+=' operation being inefficient, one optimization you can make is to reserve memory in the target string container. 如果您担心字符串'+ ='操作效率低下,则可以进行的一种优化是在目标字符串容器中保留内存。 This may avoid inefficient re-allocations of memory. 这样可以避免无效的内存重新分配。
For example: 例如:

std::string s = "copyme";
std::string b;
target.reserve(s.length()*5);
for (int index = 0; index < 5; ++index)
{
    b += s;
}

I checked the std::string implementation on my linux system and it appears this method will not cause re-allocation of the array as long as the initial reservation is large enough. 我检查了我的linux系统上的std :: string实现,并且只要初始预留足够大,此方法似乎就不会引起数组的重新分配。

template<typename _CharT, typename _Traits, typename _Alloc>
basic_string<_CharT, _Traits, _Alloc>&
basic_string<_CharT, _Traits, _Alloc>::
append(const basic_string& __str)
{
    const size_type __size = __str.size();
    if (__size)
    {
        const size_type __len = __size + this->size();
        if (__len > this->capacity() || _M_rep()->_M_is_shared())
            this->reserve(__len);
        _M_copy(_M_data() + this->size(), __str._M_data(), __size);
        _M_rep()->_M_set_length_and_sharable(__len);
    }
    return *this;
}    

A simple loop would do. 一个简单的循环就可以了。 If you are concerned about re-allocations, you can call std::string::reserve on the copy string: 如果您担心重新分配,可以在复制字符串上调用std::string::reserve

#include <string>
#include <iostream>

int main()
{
  const int num + 5;
  std::string s = "copyme";
  std::string b;
  b.reserve(s.size() * num); // reserve space for num* "copyme"
  for (int i = 0; i < num; ++i) b += s;

  std::cout << b << std::endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM