我知道StringBuffer的append()操作花费O(1)时间,与String连接相比,它避免了创建String对象的多个副本的开销.
insert(int offset,char c)怎么样?
我需要重复调用此操作,以便以相反的顺序逐个向StringBuffer对象添加新字符.例如,
StringBuffer sb = new StringBuffer();
sb.insert(0, 'c');
sb.insert(0, 'b');
sb.insert(0, 'a');
System.out.println(sb.toString()); //prints out "abc";
Run Code Online (Sandbox Code Playgroud)
在理想情况下,如果StringBuffer对象内部看起来像链接的字符列表,则每个插入(0,c)应该是O(1).我想确认是否真的如此.
在 C 中创建常量字符串的好方法是什么?无法通过对其索引位置之一进行字符分配来改变的字符串。并且在初始化后的后续执行中不能被另一个字符串替换的字符串。
我在下面的代码中尝试了 char* 和 char[] 。我尝试过使用和不使用“const”关键字。结果非常奇怪。
以下是我的代码:
#include <stdio.h>
main() {
char a []= "abc" "def";
char* b = "abcdef";
const char c [] = "abcdef";
const char* d = "abcdef";
a[1] = 'y';
b[1] = 'y';
c[1] = 'y';
d[1] = 'y';
printf("%s %s %s %s \n", a, b, c, d);
a = "overwrited";
b = "overwrited";
c = "overwrited";
d = "overwrited";
printf("%s %s %s %s \n", a, b, c, d);
}
Run Code Online (Sandbox Code Playgroud)
结果是,在第一个printf中,所有a、b、c、d都可以变异;但c和d出现警告“分配只读位置”。在第二个 printf 中,a 和 …
我试图将一个空的struct指针传入一个名为"initialize"的函数作为输出参数,然后在函数完成后我可以检索struct指针指向的对象.一些意想不到的行为发生,我不太明白.
以下是我的代码:
static void initialize(complex_struct*& infoPtr)
{
complex_struct myInfo;
infoPtr = &myInfo;
// some other codes that modify the contents of myInfo
infoPtr->input_components = 3;
}
static void myfunction()
{
complex_struct* infoPtr = nullptr;
initialize(infoPtr);
std::cout << infoPtr->input_components << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这个输出是一个任意的大整数.但我期待打印整数3.
限制:我无法修改complex_struct; 它是一个需要使用的third_party结构.另外,我需要将initialize()作为一个单独的函数的原因是我正在对complex_struct的内存分配进行性能测量.因此,将initialize()中的第一行代码移动到myfunction()并不是一个理想的解决方案.