在过去的几年里,我并没有非常使用过C语言.当我今天读到这个问题时,我遇到了一些我不熟悉的C语法.
显然在C99中,以下语法有效:
void foo(int n) {
int values[n]; //Declare a variable length array
}
Run Code Online (Sandbox Code Playgroud)
这似乎是一个非常有用的功能.有没有关于将它添加到C++标准的讨论,如果是这样,为什么它被省略?
一些潜在的原因:
C++标准规定数组大小必须是常量表达式(8.3.4.1).
是的,当然我意识到在玩具示例中可以使用std::vector<int> values(m);,但这会从堆中分配内存而不是堆栈.如果我想要一个多维数组,如:
void foo(int x, int y, int z) {
int values[x][y][z]; // Declare a variable length array
}
Run Code Online (Sandbox Code Playgroud)
该vector版本变得很笨拙:
void foo(int x, int y, int z) {
vector< vector< vector<int> > > values( /* Really painful expression here. */);
}
Run Code Online (Sandbox Code Playgroud)
切片,行和列也可能遍布整个内存.
看一下comp.std.c++这个问题的讨论很明显,这个问题在争论的两个方面都有一些非常重要的名字引起争议.毫无疑问,a std::vector总是更好的解决方案.
所以我已经得到了我最后一个问题的答案(我不知道为什么我没有想到这一点).当我没想到它的时候,我正在打印一个圆润的double使用cout.如何使用全精度cout打印double?
我的理解是它string是std命名空间的成员,为什么会出现以下情况呢?
#include <iostream>
int main()
{
using namespace std;
string myString = "Press ENTER to quit program!";
cout << "Come up and C++ me some time." << endl;
printf("Follow this command: %s", myString);
cin.get();
return 0;
}
Run Code Online (Sandbox Code Playgroud)

每次程序运行时,都会myString打印一个看似随机的3个字符的字符串,例如上面的输出.
我想知道是否存在itoa()将整数转换为字符串的替代方法,因为当我在visual Studio中运行它时会收到警告,当我尝试在Linux下构建程序时,我收到编译错误.
如何在C++中将整数转换为十六进制字符串?
我可以找到一些方法来实现它,但它们似乎主要针对C.似乎在C++中没有本地方法.这是一个非常简单的问题; 我有一个int我想转换为十六进制字符串以便以后打印.
在这种情况下
struct Foo {};
Foo meh() {
return std::move(Foo());
}
Run Code Online (Sandbox Code Playgroud)
我很确定移动是不必要的,因为新创建的Foo将是一个xvalue.
但在这种情况下呢?
struct Foo {};
Foo meh() {
Foo foo;
//do something, but knowing that foo can safely be disposed of
//but does the compiler necessarily know it?
//we may have references/pointers to foo. how could the compiler know?
return std::move(foo); //so here the move is needed, right?
}
Run Code Online (Sandbox Code Playgroud)
我认为需要采取行动吗?
如何迭代元组(使用C++ 11)?我尝试了以下方法:
for(int i=0; i<std::tuple_size<T...>::value; ++i)
std::get<i>(my_tuple).do_sth();
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
错误1:抱歉,未实现:无法将"Listener ..."扩展为固定长度的参数列表.
错误2:我不能出现在常量表达式中.
那么,我如何正确迭代元组的元素?
假设我有这样的代码:
void printHex(std::ostream& x){
x<<std::hex<<123;
}
..
int main(){
std::cout<<100; // prints 100 base 10
printHex(std::cout); //prints 123 in hex
std::cout<<73; //problem! prints 73 in hex..
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,在从函数返回后,是否有任何方法可以将cout的状态"恢复"到原来的状态?(有点像std :: boolalpha和std :: noboolalpha ..)?
谢谢.
也许这是一个愚蠢的问题,但有没有办法将布尔值转换为字符串,使得1转为"true",0转为"false"?我可以使用if语句,但很高兴知道是否有办法用语言或标准库来实现.另外,我是一个学生.:)