假设我有一个std::map<std::string, int>.std::string可以与没有std::string临时值的C字符串(const char*)进行比较.但是,map::find()似乎迫使我构造一个临时的std::string,这可能需要一个内存分配.我该如何避免这种情况?从概念上讲,它很容易,但STL似乎可以防止这种情况发生.
#include <map>
int main()
{
std::map<std::string, int> m;
m.find("Olaf");
}
Run Code Online (Sandbox Code Playgroud) const unsigned char* p;
int64_t u = ...; // ??
Run Code Online (Sandbox Code Playgroud)
从p指向的8个字节读取64位二进制小端整数的推荐方法是什么?在x64上,单个机器指令应该这样做,但是在大端硬件上需要交换.如何以最佳和便携的方式做到这一点?
Carl的解决方案很好,便携但不是最佳.这引出了一个问题:为什么C/C++没有提供更好和标准化的方法来做到这一点?这不是一个不常见的结构.
建议将字符串转换为数组的方法是什么?我正在寻找类似的东西:
template<class T, size_t N, class V>
std::array<T, N> to_array(const V& v)
{
assert(v.size() == N);
std::array<T, N> d;
std::copy(v.begin(), v.end(), d.data());
return d;
}
Run Code Online (Sandbox Code Playgroud)
C ++ 11或Boost是否提供类似的信息?别人怎么做?每次我在项目中需要此功能时,似乎都不得不自己复制/粘贴该功能,这很愚蠢。
使用std :: string的移动赋值运算符(在VC11中)需要什么?
我希望它会被自动使用,因为在任务完成后不再需要v.在这种情况下是否需要std :: move?如果是这样,我不妨使用非C++ 11交换.
#include <string>
struct user_t
{
void set_name(std::string v)
{
name_ = v;
// swap(name_, v);
// name_ = std::move(v);
}
std::string name_;
};
int main()
{
user_t u;
u.set_name("Olaf");
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我理解C++不能operator==自动为一个类定义,但为什么它不能!(a == b)用于a != b什么时候operator!=不可用但是operator==?
我知道std::rel_ops虽然我今天没有听说过它.
假设我有一个跨平台的C++库,我们称之为ylib.我的主要开发平台是Linux.我希望ylib可以由MSVC构建(2008年,2010年,11年等).
最好的方法是什么?我是否生成.vcproj文件?如果是这样,怎么样?理想情况下,我可以在不使用Windows的情况下生成它们.Windows不需要额外的依赖项.应该构建多个变体:debug dll,debug lib,release dll,release lib with dynamic runtime和release lib with static runtime.
为什么这个调用返回NULL?正则表达式错误吗?对于test输入,它不会返回 NULL。文档说 NULL 表示错误,但它可能是什么错误?
$s = hex2bin('5b5d202073205b0d0a0d0a0d0a0d0a20202020202020203a');
// $s = 'test';
$s = preg_replace('/\[\](\s|.)*\]/s', '', $s);
var_dump($s);
// PHP 7.2.10-1+0~20181001133118.7+stretch~1.gbpb6e829 (cli) (built: Oct 1 2018 13:31:18) ( NTS )
Run Code Online (Sandbox Code Playgroud) 有没有办法确保除非所有其他重载都失败,否则不选择模板重载,而不使用enable_if?
Int应该由long重载处理,但它由模板重载处理,编译器不喜欢它.
class SetProxy {
public:
void operator=(const TemplateString& value) {
dict_.SetValue(variable_, value);
}
template<class T>
void operator=(const T& value) {
dict_.SetValue(variable_, TemplateString(value.data(), value.size()));
}
void operator=(long value) {
dict_.SetIntValue(variable_, value);
}
}
Run Code Online (Sandbox Code Playgroud) 将浮点数格式化为不带尾随零的字符串的推荐方法是什么?
to_string()返回"1.350000"为sprintf。我不需要固定的小数位数...
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = to_string(1.35);
cout << s << endl;
}
Run Code Online (Sandbox Code Playgroud)