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

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();

备注

有问题随时交流~~

http://www.xdnf.cn/news/4470.html

相关文章:

  • 以太联-Intellinet 561648 户外防破坏千兆PoE延长器-- 稳定可靠,全天候守护网络连接
  • 神经网络在模式识别中的应用:从语音到视觉的智能解析
  • fedora系统详解详细版本
  • 鸿蒙开发——3.ArkTS声明式开发:构建第一个ArkTS应用
  • 基于QT(C++)实现(图形界面)校园导览系统
  • Failed building wheel for pycuda
  • AI工场全面激活电商创意链
  • 数据库系统概论-基础理论
  • PCB设计流程及注意事项
  • Czkawka:跨平台重复文件清理
  • BT回测框架Cerebro,DataFeeds和Strategies的介绍
  • [ubuntu]fatal error: Eigen/Core: No such file or directory
  • Linux:认识基础IO
  • cpp学习笔记3--class
  • 私网IP地址范围解析与应用指南
  • 【ASP.net】在Windows 11上安装IIS并测试C# Web项目的踩坑实录
  • Linux云计算训练营笔记day03(Rocky Linux中的命令)
  • 16.Excel:打印技巧
  • 深入 JavaScript 执行机制与事件循环
  • Amazing晶焱科技:系统级 EOS 测试方法 - System Level EOS Testing Method
  • 【软件设计师:数据结构】1.数据结构基础(一)
  • 如何巧妙解决 Too many connections 报错?
  • 排列组合算法:解锁数据世界的魔法钥匙
  • 剑指大规模 AI 可观测,阿里云 Prometheus 2.0 应运而生
  • WPF之高级绑定技术
  • 0509滴滴前端项目常见内容
  • 快速上手 Docker:从入门到安装的简易指南(Mac、Windows、Ubuntu)
  • SQL Server To Paimon Demo by Flink standalone cluster mode
  • 力扣1812题解
  • 二叉树的遍历与构造