当前位置: 首页 > news >正文

Python与C++类型对照及常用操作

基础类型

Python类型C++对应类型简单示例对比头文件需求
intint/int64_tPy: a = 42
C++: int a = 42;
floatdoublePy: b = 3.14
C++: double b = 3.14;
boolboolPy: c = True
C++: bool c = true;
strstd::stringPy: d = "你好"
C++: std::string d = "你好";
<string>
bytesvector<uint8_t>Py: data = b"hello"
C++: vector<uint8_t> data = {'h','e','l','l','o'};
<vector>
NonenullptrPy: empty = None
C++: auto empty = nullptr;

容器类型对照

  1. 列表(list ⇄ vector)
# Python列表操作
lst = [1, 2, 3]
lst.append(4)      # [1,2,3,4]
lst.pop()          # [1,2,3]
print(lst[1])      # 2
print(len(lst))    # 3
// C++ vector操作
#include <vector>
#include <iostream>vector<int> lst = {1, 2, 3};
lst.push_back(4);   // 添加元素
lst.pop_back();     // 移除末尾
cout << lst[1];     // 访问元素 (2)
cout << lst.size(); // 获取大小// 遍历vector的三种方式:
// 1. 传统for
for(size_t i=0; i<lst.size(); ++i) {cout << lst[i] << " ";
}// 2. 范围for
for(int num : lst) {cout << num << " ";
}// 3. 使用迭代器
for(auto it=lst.begin(); it!=lst.end(); ++it) {cout << *it << " ";
}
  1. 字典(dict ⇄ unordered_map)
# Python字典操作
d = {"name": "小明", "age": 18}
print(d["name"])       # "小明"
print("age" in d)      # True
d["score"] = 90        # 添加键值
for k, v in d.items():  # 遍历print(f"{k}:{v}")
// C++ unordered_map操作
#include <unordered_map>
#include <string>
#include <iostream>unordered_map<string, int> d = {{"name", "小明"},{"age", 18}
};cout << d["name"];          // 访问值
cout << (d.count("age")>0); // 检查键是否存在
d["score"] = 90;           // 添加/修改键值// 遍历map的两种方式:
// 1. 使用auto&
for(auto& pair : d) {cout << pair.first << ":" << pair.second << endl;
}
  1. 集合(set ⇄ unordered_set)
# Python集合操作
s = {1, 2, 2, 3}  # {1,2,3}
s.add(4)          # {1,2,3,4}
print(2 in s)     # True
// C++ unordered_set操作
#include <unordered_set>
#include <iostream>unordered_set<int> s = {1, 2, 3};
s.insert(4);               // 添加元素
cout << (s.count(2)>0);    // 检查存在性// 遍历集合
for(int num : s) {cout << num << " ";
}

常用操作

  1. 简化打印函数
#include <iostream>
#include <vector>
#include <unordered_map>// 打印vector
template<typename T>
void print(const vector<T>& vec) {for(const auto& item : vec) {cout << item << " ";}cout << endl;
}// 打印map
template<typename K, typename V>
void print(const unordered_map<K,V>& map) {for(const auto& pair : map) {cout << pair.first << ":" << pair.second << " ";}cout << endl;
}// 使用示例
vector<int> nums = {1, 2, 3};
unordered_map<string, int> dict = {{"a",1}, {"b",2}};
print(nums);  // 输出: 1 2 3
print(dict);  // 输出: a:1 b:2
  1. range模拟器
// 实现Python风格的range
vector<int> range(int stop) {vector<int> result;for(int i=0; i<stop; ++i) {result.push_back(i);}return result;
}vector<int> range(int start, int stop) {vector<int> result;for(int i=start; i<stop; ++i) {result.push_back(i);}return result;
}// 使用示例
for(int i : range(5)) {cout << i << " ";  // 0 1 2 3 4
}
  1. 文件操作对比
# Python文件操作
with open("data.txt", "w") as f:f.write("Hello\nWorld")with open("data.txt", "r") as f:for line in f:print(line.strip())
// C++文件操作
#include <fstream>
#include <string>
#include <iostream>// 写入文件
ofstream out("data.txt");
out << "Hello\nWorld";
out.close();// 读取文件
ifstream in("data.txt");
string line;
while(getline(in, line)) {cout << line << endl;
}
in.close();

备注

有问题随时交流~~

相关文章:

  • 如何在24G显存机器上搭建一个超过gpt效果的DeepSeek-R1?
  • 将本地项目提交到新建的git仓库
  • 项目成果未达预期,如何补救
  • 小王包子铺的融资过程以及IPO上市过程
  • 记录学习《手动学习深度学习》这本书的笔记(十)
  • 【高级IO】多路转接之Epoll
  • RPG9.修改武器GA
  • 【软件设计师:数据结构】2.数据结构基础(二)
  • 《Python星球日记》 第45天:KNN 与 SVM 分类器
  • C语言 指针(8)
  • 从彼得·蒂尔四象限看 Crypto「情绪变迁」:从密码朋克转向「标准化追求者」
  • STM32的网络天气时钟项目
  • Kafka Controller的作用是什么?故障时如何恢复? (管理分区和副本状态;通过ZooKeeper选举新Controller)
  • 理解与清理 Docker 中的悬空镜像(Dangling Images)
  • 大语言模型中的“温度”参数到底是什么?如何正确设置?
  • 终端安全登录系统的必要性及安当SLA双因素认证解决方案深度解析
  • MySQL基础关键_010_数据库设计三范式
  • 7.2.安全防御
  • Java版ERP管理系统源码(springboot+VUE+Uniapp)
  • Android学习总结之MMKV(代替SharedPreferences)
  • 媒体谈法院就“行人相撞案”道歉:执法公正,普法莫拉开“距离”
  • 宇数科技王兴兴:第一桶金来自上海,欢迎上海的年轻人加入
  • 匈牙利外长称匈方已驱逐两名乌克兰外交官
  • 人民日报评“组团退演出服”:市场经济诚信原则需全社会维护
  • 中华人民共和国和俄罗斯联邦在纪念中国人民抗日战争、苏联伟大卫国战争胜利和联合国成立80周年之际关于进一步深化中俄新时代全面战略协作伙伴关系的联合声明
  • 见微知沪|优化营商环境,上海为何要当“细节控”自我加压?