【问题标题】:string::swap complexity under Visual StudioVisual Studio 下的 string::swap 复杂度
【发布时间】:2014-08-08 10:47:45
【问题描述】:

cppreference 页面说 std::basic_string::swap 具有恒定的复杂性。正如我假设的那样,这意味着复制内容不会发生,只有指针交换或类似操作。我写了一段测试代码,体验了一下,在VS2010下确实可以移动内容。测试代码:

std::string s1("almafa");
std::string s2("kortefa");
std::cout << "s1.c_str(): "<< (void*)s1.c_str() << std::endl;
std::cout << "s2.c_str(): "<< (void*)s2.c_str() << std::endl;
std::cout << "SWAP!" << std::endl;
s1.swap(s2);
std::cout << "s1.c_str(): "<< (void*)s1.c_str() << std::endl;
std::cout << "s2.c_str(): "<< (void*)s2.c_str() << std::endl;

g++ 4.6.3 上的输出

s1.c_str(): 0x22fe028
s2.c_str(): 0x22fe058
SWAP!
s1.c_str(): 0x22fe058
s2.c_str(): 0x22fe028

VS2010 上的输出

s1.c_str(): 000000000022E2D0
s2.c_str(): 000000000022E320
SWAP!
s1.c_str(): 000000000022E2D0
s2.c_str(): 000000000022E320

是与标准有偏差还是发生了我不知道的事情?

【问题讨论】:

  • 使字符串 loooooooooooooooooooooonger.

标签: c++ visual-studio-2010 stl


【解决方案1】:

std::string 的一些实现使用了短字符串优化

来自How is std::string implemented?

“短字符串优化”(SSO) 实现。在这个变体中,对象包含通常指向数据的指针、长度、动态分配缓冲区的大小等。但如果字符串足够短,它将使用该区域来保存字符串,而不是动态分配缓冲区。

因此,在您的情况下,交换会复制但大小固定,因此 O(1)。

【讨论】:

  • 我应该买一个vector&lt;char&gt; :-)
猜你喜欢
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 2010-09-23
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
相关资源
最近更新 更多