Python and C++ code comparison

I have the following python code

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 is array defined and i and j is also defined.

Following is how I have converted this into 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) {
}

Is this conversion correct?

Answers


As another person remarked, the width used in two places is probably incorrect.

Assuming that, here's a comparision of direct translation from Python versus C++-like code:

#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()
{}

Cheers & hth.,


Almost. You have two differences: in Python, you have i+m<b and j+n<l, which makes me think b!=l.

In your C++ code, you have i + m < width and j + n < width, where width is the same.

If width == b == l, then everything's fine.

Actually, depends on how image is defined. The image[i + m][j + n ] == 0 is what bothers me (the part with ==0)

As the @Avinash comment says, image is vector< vector< int > >, so the code is fine.


Need Your Help

Difference between Applet and Servlet and their usages

java servlets applet

What is the difference between an Applet and a Servlet and what are a few examples on how each of them are used? I am new to networking am I am wondering how these things are different.