C++ 11中的原始字符串文字是非常好的,除了显示它们的明显方法导致冗余换行\n作为第一个字符.
考虑这个例子:
some_code();
std::string text = R"(
This is the first line.
This is the second line.
This is the third line.
)";
more_code();
Run Code Online (Sandbox Code Playgroud)
明显的解决方法看起来很难看:
some_code();
std::string text = R"(This is the first line.
This is the second line.
This is the third line.
)";
more_code();
Run Code Online (Sandbox Code Playgroud)
有没有人找到一个优雅的解决方案?
默认的Emacs C++模式(cc-mode)仍然无法识别许多C++ 11功能.一个恼人的问题是它对用作函数参数的lambda函数应用了太多的缩进:
std::vector<int> ar(4);
std::generate_n(std::begin(ar), 4, [] {
static int g_i;
return g_i++;
});
std::for_each(std::begin(ar), std::end(ar), [](int i) {
std::cout << " " << i;
});
bool b = std::is_sorted(std::begin(ar), std::end(ar), [&](int l, int r) {
return l<r;
});
std::cout << " " << b << "\n";
Run Code Online (Sandbox Code Playgroud)
理想情况下,人们会更喜欢:
std::vector<int> ar(4);
std::generate_n(std::begin(ar), 4, [] {
static int g_i;
return g_i++;
});
std::for_each(std::begin(ar), std::end(ar), [](int i) {
std::cout << " " << i;
});
bool b = std::is_sorted(std::begin(ar), std::end(ar), …Run Code Online (Sandbox Code Playgroud) 我不清楚C++ 11标准中hash<T>应该定义用户定义的仿函数.
例如,在23.5.2 Header中<unordered_map>,它显示:
template <class Key,
class T,
class Hash = hash<Key>,
class Pred = std::equal_to<Key>,
class Alloc = std::allocator<std::pair<const Key, T> > >
class unordered_map;
Run Code Online (Sandbox Code Playgroud)
这表明,默认情况下,hash<T>在全局命名空间equal_to<>中搜索,而在std命名空间中搜索.
为什么名称空间hash<>与equal_to<>?之间存在差异?
(实际上,在http://www.cplusplus.com/reference/unordered_map/unordered_map/的描述中,都没有指定std命名空间.)
因此,在hash<>为用户类型定义仿函数时,是应该将它包含在namespace std { }块中,还是可以保留在当前命名空间中?
如果代码没有using namespace std;,那么STL容器如何unordered_map知道在std命名空间中查找hash<>与基元类型相关联的预定义仿函数?看起来默认Hash = hash<Key>会找不到这些.
对不起,如果这些都是愚蠢的问题..
给定一个dataclass实例,我想print()或str()仅列出非默认字段值。dataclass当有许多字段并且只有少数字段发生更改时,这非常有用。
@dataclasses.dataclass
class X:
a: int = 1
b: bool = False
c: float = 2.0
x = X(b=True)
print(x) # Desired output: X(b=True)
Run Code Online (Sandbox Code Playgroud) 的std::move(),因为它检测到在Visual Studio 2013(与调试配置)编译时在下面的代码发出警告,运行时dest是一个nullptr.但是,源范围是空的,因此dest永远不应该访问.C++标准可能不清楚是否允许这样做?它声明: 要求:结果不应在[first,last]范围内.
A nullptr似乎满足了这个要求.
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec;
int* dest = nullptr;
// The range [begin(vec),end(vec)) is empty, so dest should never be accessed.
// However, it results in an assertion warning in VS2013.
std::move(std::begin(vec), std::end(vec), dest);
}
Run Code Online (Sandbox Code Playgroud) 我跟踪了一个错误,即使用__m128(SSE向量)作为std :: unordered_map中的值.这会导致mingw32 g ++ 4.7.2的运行时分段错误.
请参阅下面的示例.这有什么理由会失败吗?或者,可能有一个解决方法?(我尝试将值包装在一个类中,但它没有帮助.)谢谢.
#include <unordered_map>
#include <xmmintrin.h> // __m128
#include <iostream>
int main()
{
std::unordered_map<int,__m128> m;
std::cerr << "still ok\n";
m[0] = __m128();
std::cerr << "crash in previous statement\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译设置:g ++ -march = native -std = c ++ 11
关于模板化函数中的完美转发的广泛讨论,允许有效地将左值或右值参数作为参数传递给其他函数.
但是,我无法找到关于完美回归或等效完美传递的讨论.(相关问题完美传递并未完全解决此问题.)
考虑修改范围的函数的情况,并应返回修改的范围.我们需要两个单独的函数来有效地解决左值和右值参数的情况:
// Given a reference to an lvalue range, return a reference to the same modified range.
// (There is no allocation or move.)
template<typename T> T& sortr(T& r) {
std::sort(std::begin(r),std::end(r));
return r;
}
// Given an rvalue range, return the same range via (hopefully) a move construction.
template<typename T> T sortr(T&& r) {
std::sort(std::begin(r),std::end(r));
return std::move(r);
}
Run Code Online (Sandbox Code Playgroud)
当然,包括这两个定义会导致歧义错误,因为第二个定义也与左值引用匹配.
一个激励性的例子(和测试用途)如下:
#include <iostream>
#include <vector>
#include <algorithm>
std::ostream& operator<<(std::ostream& os, const std::vector<int>& v) …Run Code Online (Sandbox Code Playgroud) 创建所有通道具有恒定标量的彩色图像很容易:
height, width = 3, 4
shape = (height, width)
num_channels = 3
scalar_value = 0.5
image = np.full((*shape, num_channels), scalar_value)
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法来创建具有恒定颜色矢量的图像?
vector_value = (0.3, 0.4, 0.5) # e.g. (red, green, blue)
image = create_new(shape, vector_value)
Run Code Online (Sandbox Code Playgroud)
这可以使用自定义函数来完成:
def create_new(shape, vector_value):
image = np.empty((*shape, len(vector_value)))
image[...] = vector_value
return image
Run Code Online (Sandbox Code Playgroud)
但我想知道是否可以使用简单的numpy表达式来完成此操作。
我想要一个从unordered_set中"删除一个元素"的函数.
但是,当使用erase(begin())实现它时,它变得非常慢.(这是用g ++ - 4.5.3;也许begin()必须遍历大量的空哈希桶?)
请参阅下面的示例代码,并提供令人惊讶的计时.
是否有其他方法可以实现"删除一个元素",从而提高效率?(我确实想允许其他干预集合操作,这会使迭代器无效.)
#include <unordered_set>
#include <iostream>
#include <chrono>
using namespace std;
struct Timer {
Timer(string s) : _s(s), _start(Clock::now()) { }
~Timer() {
auto t=chrono::duration_cast<chrono::milliseconds>(Clock::now()-_start).count();
cerr << "Timer(" << _s << ") = " << t << "ms\n";
}
private:
typedef chrono::high_resolution_clock Clock;
string _s;
Clock::time_point _start;
};
int main()
{
unordered_set<int> s;
const int num=200000;
{ Timer t("insert"); for (int i=0;i<num;i++) { s.insert(i); } }
{ Timer t("remove half"); for (int i=0;i<num/2;i++) { s.erase(s.begin()); …Run Code Online (Sandbox Code Playgroud) 要获取当前缓冲区的文件名,以下是等效的吗?
(1)(buffer-file-name)和
(2)buffer-file-name.
是否有理由偏爱另一个?
谢谢.
在学习模板参数包时,我正在尝试编写一个聪明,简单的函数来有效地将两个或多个std::vector容器附加到一起.
以下是两个初始解决方案.
版本1优雅但有缺陷,因为它在参数包的扩展期间依赖于副作用,并且评估的顺序是未定义的.
版本2有效,但依赖于需要两种情况的辅助函数.呸.
你能看出你是否能想出一个更简单的解决方案吗?(为了提高效率,不应多次复制矢量数据.)
#include <vector>
#include <iostream>
// Append all elements of v2 to the end of v1.
template<typename T>
void append_to_vector(std::vector<T>& v1, const std::vector<T>& v2) {
for (auto& e : v2) v1.push_back(e);
}
// Expand a template parameter pack for side effects.
template<typename... A> void ignore_all(const A&...) { }
// Version 1: Concatenate two or more std::vector<> containers into one.
// Nicely simple, but buggy as the order of evaluation is undefined.
template<typename T, typename... …Run Code Online (Sandbox Code Playgroud) 在GNU中Makefile,有两种类型的变量:
# simple variable (immediate evaluation):
VAR := some_assignment
# recursively expanded variable (deferred evaluation):
VAR = some_assignment
Run Code Online (Sandbox Code Playgroud)
可以使用以下方法将其追加到递归扩展的变量中:
IMMEDIATE += DEFERRED or IMMEDIATE
Run Code Online (Sandbox Code Playgroud)
对于追加运算符'+ =',如果先前已将该变量设置为简单变量(':='或':: ='),则认为右侧是立即数,否则推迟。
有没有什么办法来预先考虑到递归扩展变量?
我的激励示例是在以下方面引入一个新的库$(LDLIBS):
# Unfortunately, newlib gets added to the end rather than the beginning.
LDLIBS += $(if $(later_condition),newlib.a)
# Unfortunately, the expression is evaluated now rather than being deferred.
LDLIBS := $(if $(later_condition),newlib.a) $(LDLIBS)
Run Code Online (Sandbox Code Playgroud)