我正在使用JsonCpp来构建一个JSON对象.一旦构建了对象,有没有办法让对象成为一个std::string?
C++ 11介绍了std::to_string,所以我看了一个实现:它在vsnprintf内部调用.好的,但为什么总是将size参数设置为类型大小的4倍?
inline string
to_string(int __val)
{ return __gnu_cxx::__to_xstring<string>(&std::vsnprintf, 4 * sizeof(int),
"%d", __val); }
inline string
to_string(unsigned __val)
{ return __gnu_cxx::__to_xstring<string>(&std::vsnprintf,
4 * sizeof(unsigned),
"%u", __val); }
inline string
to_string(long __val)
{ return __gnu_cxx::__to_xstring<string>(&std::vsnprintf, 4 * sizeof(long),
"%ld", __val); }
Run Code Online (Sandbox Code Playgroud) 是否由标准保证,std::string如果从较小的字符串重新分配,则不会自发地回放分配的内存?
换一种说法:
std::string str = "Some quite long string, which needs a lot of memory";
str = "";
str = "A new quite long but smaller string"; // Guaranteed to not result in a heap allocation?
Run Code Online (Sandbox Code Playgroud)
我问,因为我依赖于此以避免堆碎片.
我改变了我的类使用std :: string(基于我在这里得到的答案,但是我有一个函数返回wchar_t*.如何将它转换为std :: string?
我试过这个:
std::string test = args.OptionArg();
Run Code Online (Sandbox Code Playgroud)
但它说错误C2440:'初始化':无法从'wchar_t*'转换为'std :: basic_string <_Elem,_Traits,_Ax>'
显然,constexpr std::string尚未添加到GCC的libstdc++中(从 GCC v11.2 开始)。
这段代码:
#include <iostream>
#include <string>
int main()
{
constexpr std::string str { "Where is the constexpr std::string support?"};
std::cout << str << '\n';
}
Run Code Online (Sandbox Code Playgroud)
不编译:
#include <iostream>
#include <string>
int main()
{
constexpr std::string str { "Where is the constexpr std::string support?"};
std::cout << str << '\n';
}
Run Code Online (Sandbox Code Playgroud)
char当字符串包含超过 16秒(因为 GCC 的 SSO 缓冲区大小为 16)时,此类字符串将如何工作?简短的解释是什么?一个简单的构造函数会在堆栈上创建字符串对象并且从不使用动态分配吗?
这段代码:
std::cout << "is_trivially_constructible: "
<< std::boolalpha << std::is_trivially_constructible<const std::string>::value << '\n'; …Run Code Online (Sandbox Code Playgroud) 以前这是std::string::c_str()工作,但是从C ++ 11开始,data()它也提供了工作,为什么还要c_str()添加null终止字符std::string::data()?在我看来,这似乎是在浪费CPU周期,如果null终止字符根本不相关而仅data()使用,C ++ 03编译器就不必关心终止符,也不必每次调整字符串大小时,都必须向终止符写入0,但是由于data()-null-guarantee,C ++ 11编译器不得不浪费每次写入字符串大小时都要写入0的周期,因此,这可能会使代码变慢,我想他们有一定理由要添加该保证,那是什么?
我发现的行为std::string::find与标准C ++容器不一致。
例如
std::map<int, int> myMap = {{1, 2}};
auto it = myMap.find(10); // it == myMap.end()
Run Code Online (Sandbox Code Playgroud)
但是对于一串,
std::string myStr = "hello";
auto it = myStr.find('!'); // it == std::string::npos
Run Code Online (Sandbox Code Playgroud)
为什么不应该失败的myStr.find('!')回报myStr.end(),而不是std::string::npos?
由于std::string与其他容器相比,它有些特殊,所以我想知道这背后是否有真正的原因。(令人惊讶的是,我找不到任何人在任何地方对此进行质疑)。
我的程序之一超出了我使用的时间限制fans = fans + s[i],而当我正在使用fans += s[i]它的时候却被接受了……为什么会发生这种情况?为了进一步说明,迷是一个字符串,而s也是一个字符串,因此在遍历字符串si时只需要s的一些字符,因此我创建了一个新的字符串迷。现在有两种方法可以在新字符串中添加字符粉丝 问题在下面提到
fans = fans + s[i]; // gives Time limit exceeded
fans += s[i]; // runs successfully
Run Code Online (Sandbox Code Playgroud) 我有一个需要编码字符串的函数,它需要能够接受0x00作为有效的'字节'.我的程序需要检查字符串的长度,但是如果我传递"\x00"给std::string该length()方法返回0.
即使字符串是单个空字符,如何获得实际长度?