我注意到c ++中的allocator为void类型提供了特化.这样做有什么特别的目的吗?为void类型分配内存没有意义,对吧?
据说这里,这是因为异常规范的.我不明白.这个问题与异常规范有什么关系吗?
在通用编程和STL(中文版)一书中,它说:
X x = X()将调用复制构造函数.
这对我来说似乎有点奇怪.我写了一个像这样的测试程序
#include <iostream>
class Test {
public:
Test() {
std::cout << "This is ctor\n";
}
Test(const Test&) {
std::cout << "This is copy-ctor\n";
}
};
int main(int argc, char** argv)
{
Test t = Test();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是"This is ctor".好的,现在我很困惑,这是对的吗?
以下程序无法编译.但如果我不评论operator==,它会编译.operator==我已经提供的时候仍然需要为什么FooEqual
#include <cstddef>
#include <unordered_set>
struct Foo {
};
struct FooHasher {
size_t operator()(const Foo&) const {
return 1;
}
};
struct FooEqual {
bool operator()(const Foo& lhs, const Foo& rhs) const {
return true;
}
};
// bool operator==(const Foo& lhs, const Foo& rhs) {
// return true;
// }
int main() {
std::unordered_set<Foo, FooHasher, FooEqual> s1;
std::unordered_set<Foo, FooHasher, FooEqual> s2;
(void)(s1 == s2);
return 0;
}
Run Code Online (Sandbox Code Playgroud) #include <iostream>
template <class T>
void foo(T) {
std::cout << "foo(T)" << std::endl;
}
template <class T>
void foo(T*) { //#3
std::cout << "foo(T*)" << std::endl;
}
#define TEST
#ifdef TEST
template <>
void foo(int*) { //#1
std::cout << "foo(int*)" << std::endl;
}
#else
template <>
void foo<int*>(int*) { //#2
std::cout << "foo<int*>(int*)" << std::endl;
}
#endif
int main(int argc, char **argv) {
int* p = 0;
foo(p);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
#1和#2之间有什么区别.如果我定义TEST,#1工作.但如果我评论它,#3工作......这是编写函数模板专业化的正确方法......
可能重复:
javascript数字 - 不可变
我读过Douglas Crockford的书:JavaScript:the Good Parts.它说JavaScript中的数字是不可变的.但JavaScript中的数字是按值复制的,我们可以使用operator ++来更改值.那么为什么说这是不可改变的呢?而且,如果它是不可变的,为什么数字是按值复制的?
问题陈述:
给定一个整数n,计算所有小于或等于n的非负整数中出现的数字1的总数。
例如:给定 n = 13,返回 6,因为数字 1 出现在以下数字中:1、10、11、12、13。
有效的解决方案:
int countDigitOne(int n) {
if (n <= 0) return 0;
int q = n, x = 1, ans = 0;
do {
int digit = q % 10;
q /= 10;
ans += q * x;
if (digit == 1) ans += n % x + 1;
if (digit > 1) ans += x;
x *= 10;
} while (q > 0);
return ans;
}
Run Code Online (Sandbox Code Playgroud)
我的问题:
我在其中一个论坛中找到了该问题的解决方案,但我发现很难理解该解决方案。我明白这是一个非常简单的,但请详细解释帮助我。
谢谢
c++ ×5
allocator ×2
stl ×2
algorithm ×1
c++11 ×1
constructor ×1
javascript ×1
math ×1
templates ×1