Python和c++代码比较

Python and C++ code comparison

本文关键字:比较 代码 c++ Python      更新时间:2023-10-16

我有以下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是数组定义的,ij也是数组定义的。

下面是我如何将其转换为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<bj+n<l,这让我认为是b!=l

在您的C++代码中,您有i + m < widthj + 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'){}