Python和c++代码比较
Python and C++ code comparison
我有以下python
代码
for m,n in [(-1,1),(-1,0),(-1,-1)] if 0<=i+m<b and 0<=j+n<l and image[i+m][j+n] == '0']
image
是数组定义的,i
和j
也是数组定义的。
下面是我如何将其转换为C++
std::vector<std::pair<int,int> > direction;
direction.push_back(std::make_pair(-1,1));
direction.push_back(std::make_pair(-1,0));
direction.push_back(std::make_pair(-1,-1));
for ( std::vector<std::pair<int,int> >::iterator itr = direction.begin();
itr != direction.end(); ++itr) {
int m = (*itr).first;
int n = (*itr).second;
if ( (0 <= i + m && i + m < width ) &&
(0 <= j + n && j + n < width ) &&
image[i + m][j + n ] == 0) {
}
这个转换正确吗?
正如另一个人所说,两个地方使用的width
可能是不正确的。
假设是这样,下面是从Python直接翻译与类c++代码的比较:
#include <iostream>
#include <list>
#include <utility>
#include <vector>
using namespace std;
void likeCPlusPlus()
{
int i = 666, j = 666, width = 666, height = 666, image[666][666];
for( int dy = 1; dy >= -1; --dy )
{
int const dx = -1;
int const x = i + dx;
int const y = j + dy;
if(
0 <= x && x < width &&
0 <= y && y < height &&
image[x][y] == 0
)
{}
}
}
void likePythonInCPlusPlus()
{
int i = 666, j = 666, width = 666, image[666][666];
std::vector<std::pair<int,int> > direction;
direction.push_back(std::make_pair(-1,1));
direction.push_back(std::make_pair(-1,0));
direction.push_back(std::make_pair(-1,-1));
for ( std::vector<std::pair<int,int> >::iterator itr = direction.begin();
itr != direction.end(); ++itr)
{
int m = (*itr).first;
int n = (*itr).second;
if ( (0 <= i + m && i + m < width ) &&
(0 <= j + n && j + n < width ) &&
image[i + m][j + n ] == 0)
{}
}
}
int main()
{}
差不多了。你有两个不同:在Python
中,你有i+m<b
和j+n<l
,这让我认为是b!=l
。
在您的C++
代码中,您有i + m < width
和j + n < width
,其中width
是相同的。
如果width == b == l
,那么一切都很好。
实际上,取决于image
是如何定义的。image[i + m][j + n ] == 0
是困扰我的(==0
的部分)
正如@Avinash评论所说,图像是vector< vector< int > >
,所以代码是好的
如果它确实是一个硬编码常量,则不需要在运行时构建该向量。只做:
const std::pair<int,int> list[] = { {-1,1}, {-1,0}, {-1,-1} };
for (int index = 0; index < sizeof(list)/sizeof(*list); ++index)
{
int m = list[index].first;
int n = list[index].second;
...
}
如果允许c++ 0x,或者
const struct { int first, second; } list[] = { {-1,1}, {-1,0}, {-1,-1} };
...
如果不是。否则,翻译看起来是可信的。
如果您不想在c++中复制Python的习惯用法,可以将代码简化为:
for (int n = 1; n >= -1; --n) {
const int m = -1;
if (...
以下工作在c++1z下:
#include <vector>
using namespace std;
for( auto [m,n] : vector<tuple<int,int> >{{-1,1}, {-1,0}, {-1,-1}})
if(0<=i+m<b and 0<=j+n<l and image[i+m][j+n] == '0'){}
相关文章:
- 黑客兰克中的错误比较三元组代码
- 我想在C++代码中比较这三个术语
- 将 ProcessEntry32.szExeFile 与用户输入的数据进行比较时,C++ _wcsicmp代码未编译
- (C++)比较两段代码,一段有效,一段无效,无法找出区别
- 代码比较:就效率而言,哪种代码更好用?
- C++按字符串调用函数,比较PHP的性能,如何在C++中优化代码
- 使用OTool进行了重构代码的二进制比较
- 如何比较两段代码的性能
- 可与Python中的array[++i]和array[i++]进行比较的代码
- 将错误代码枚举与 std::error_code 进行比较
- 此代码对于重载比较运算符是否正确
- if条件下两个字符串比较的优化代码
- OpenCV代码将存储在列表中的描述符与新的图像描述符进行比较
- 移植将 32 位浮点数与使用 64 位进行比较的代码,此值表示什么
- 如何通过 ascii 代码比较 3 个字符
- 运行时间比较 - 类似的代码运行速度慢 4 倍
- C++代码性能字符串进行比较
- 使用来自poitr的OPENCV代码进行图像比较
- 有没有一种更简单的方法可以像在java中使用包一样在C++中重用代码?制作头文件比较复杂
- ULP 比较代码