c++使用auto的注意事项

1.使用auto也能在一条语句中声明多个变量。因为一条声明语句只能有一个基本数据类型,所以该语句中所有变量的初始基本类型都必须一样:

auto i = 0,*p=&i; //正确:i是整数、p是整型指针。

auto sz = 0,pi = 3.14; //错误:sz和pi的类型不一致。

2.const auto &j = 42;//正确:可以为常量引用绑定字面值。

3.auto &h = 42;//错误:不能为非常量引用绑定字面值。

3.要在一条语句中定义多个变量,切记,符号&和*只从属于某个声明符,而非基本数据类型的一部分,因此初始值必须是同一种类型:

int i = 0;

const ci = i;

auto &n = i,*p2 = &ci;//错误:i的类型是int而&ci的类型是const int。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是关于哈夫曼树在C++注意事项: 1. 哈夫曼树是一种二叉树,因此需要定义一个二叉树的结构体或***类。 3. 在构造哈夫曼树时,需要将节点按照权值从小到大排序,因此需要定义一个比较函数或者重载运算符来实现排序。 4. 在构造哈夫曼树时,需要使用递归的方法来构造树,因此需要定义一个递归函数来实现。 5. 在编码和解码时,需要使用哈希表来存储字符和对应的编码,因此需要定义一个哈希表的结构体或类来实现。 以下是一个简单的C++代码示例,用于构造哈夫曼树和进行编码和解码: ```c++ #include <iostream> #include <queue> #include <unordered_map> using namespace std; // 定义哈夫曼树节点结构体 struct HuffmanNode { char ch; // 字符 int freq; // 权值 HuffmanNode *left, *right; // 左右子节点 HuffmanNode(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {} }; // 定义最小堆的比较函数 struct Compare { bool operator()(HuffmanNode* a, HuffmanNode* b) { return a->freq > b->freq; } }; // 构造哈夫曼树 HuffmanNode* buildHuffmanTree(string s) { // 统计字符出现的频率 unordered_map<char, int> freq; for (char c : s) { freq[c]++; } // 将字符和对应的频率存储到优先队列 priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq; for (auto p : freq) { pq.push(new HuffmanNode(p.first, p.second)); } // 构造哈夫曼树 while (pq.size() > 1) { HuffmanNode* left = pq.top(); pq.pop(); HuffmanNode* right = pq.top(); pq.pop(); HuffmanNode* parent = new HuffmanNode('$', left->freq + right->freq); parent->left = left; parent->right = right; pq.push(parent); } return pq.top(); } // 递归编码 void encode(HuffmanNode* root, string code, unordered_map<char, string>& table) { if (!root) { return; } if (root->ch != '$') { table[root->ch] = code; } encode(root->left, code + "0", table); encode(root->right, code + "1", table); } // 哈夫曼编码 string huffmanEncode(string s) { // 构造哈夫曼树 HuffmanNode* root = buildHuffmanTree(s); // 递归编码 unordered_map<char, string> table; encode(root, "", table); // 将字符串编码为二进制串 string res = ""; for (char c : s) { res += table[c]; } return res; } // 哈夫曼解码 string huffmanDecode(string s, HuffmanNode* root) { string res = ""; HuffmanNode* cur = root; for (char c : s) { if (c == '0') { cur = cur->left; } else { cur = cur->right; } if (cur->ch != '$') { res += cur->ch; cur = root; } } return res; } int main() { string s = "hello world"; string encoded = huffmanEncode(s); cout << "Encoded string: " << encoded << endl; HuffmanNode* root = buildHuffmanTree(s); string decoded = huffmanDecode(encoded, root); cout << "Decoded string: " << decoded << endl; return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值