所以我写了这段代码->
#include <iostream>
#include <bitset>
int main(){
int num, temp, digits = 0;
std::cin >> num;
temp = num;
while(temp){
temp /= 10;
++digits;
}
const int size = digits;
std::bitset<size> a(num);
std::cout << a << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
位集容器不接受 const 整数大小作为参数并抛出错误 - Non-type template argument is not a constant expression。我想知道为什么会发生这种情况,因为大小已被声明为常量,并且它的值在程序运行时不会改变?
所以我编写了这段代码来将元素添加到二叉树中.如下图所示.
typedef struct node{
int key;
node *right;
node *left;
}*nodePtr;
nodePtr root = NULL // As global variable.
void addElement(int key, nodePtr tempRoot){
if(tempRoot!=NULL){
if(tempRoot->key > key){
if(tempRoot->left!=NULL)
addElement(key, tempRoot->left);
else
tempRoot->left = createLeaf(key);
}
else if(tempRoot->key < key){
if(tempRoot->right!=NULL)
addElement(key, tempRoot->right);
else
tempRoot->right = createLeaf(key);
}
}else if(tempRoot==NULL)
tempRoot = createLeaf(key);
}
int main(){
int arr[] = {50,45,23,10,8,1,2,54,6,7,76,78,90,100,52,87,67,69,80,90};
for(int i=0; i<20; i++){
addElement(arr[i], root);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题是当我尝试打印树时,此代码不会向树中添加任何内容.但是,如果我用此代码替换代码的最后部分;
else if(root==NULL)
root = createLeaf(key);
Run Code Online (Sandbox Code Playgroud)
为什么会这样?