简体   繁体   中英

How to convert python `for` loops to c++

I am practicing c++. I need to convert these 2 codes to c++. I am having trouble with the for loop conversion like in the next example:


    # Cuenta todos los números enteros que estén en una lista
import random

def cuenta_pares(numeros):
    cuenta = 0
    for numero in numeros:
        if numero % 2 == 0:
            cuenta += 1

    return cuenta

def cuenta_impares(numeros):
    cuenta = 0
    for idx in range(len(numeros)):
        if numeros[idx] % 2 != 0:
            cuenta += 1

    return cuenta

def main():

    terminos = int(input("Cuántos numeros quieres que tenga la lista: "))
    numeros = []
    for id in range(terminos):
        numeros.append(random.randint(1, 20))

    pares = cuenta_pares(numeros)
    impares = cuenta_impares(numeros)

    print("Tu lista es: ", numeros)
    print(f"Tu lista tiene {pares} numeros pares")
    print(f"Tu lista tiene {impares} numeros impares")

main()

Also the next example has the for loops. I already managed to declare the variables but haven't been able to manage the for loops. and

    def cuadrado(width, height):

    if width % 2 == 0:
        width += 1
    if height % 2 ==  0:
        height +=1

    for row in range(height):
        for col in range(width):
            if 0 < row < height - 1 and 0 < col < width - 1:
                print(" ", end = "")
            elif col % 2 == 0:
                print("+", end = "")
            else:
                print("-", end = "")
        print()

def main():
    alto = int(input("Dame el alto del cuadrado: "))
    ancho = int(input("Dame el ancho del cuadrado: "))

    cuadrado(ancho, alto)

main()

The C++ equivalent of the Python

for x in range(n):

will be

for (int x = 0; x < n; ++x)

C++ (since C++11) also provides a range-base for loop to iterate over containers, including native arrays, std::array, std::vector, etc.

for (const auto& element : container)

For loops in c++ look like this:

for(int i = 0; i < max_iter; i++) {
    // do something
}

You can also iterate over an array like this:

int array[] = {7, 8, 1, 5, 7, 10, 6};

for(int number : array) {
    // do something with number as a part of array
}

I'll leave the rest on you. Good luck:)

With a little helper class

class range {
    class iterator {
    public:
        iterator(int i) : i_(i) {}

        int operator*() const { return i_; }
        void operator++() { ++i_; }
        bool operator!=(iterator other) const { return i_ != other.i_; }

    private:
        int i_;
    };

public:
    range(int first, int last) : first_(first), last_(last) {}
    range(int last) : range(0, last) {}

    iterator begin() const { return iterator(first_); }
    iterator end() const { return iterator(last_); }

private:
    const int first_;
    const int last_;
};

you can write:

for (auto i : range(4))
    std::cout << i << ' ';        // prints 0 1 2 3

for (auto i : range(0, 5))
    std::cout << i << ' ';        // prints 0 1 2 3 4

Isaac

The structure in C++ for the loops is:

for(declaration of the counter variable;condition to loop; increment of the variable){
    do in the loop
    }

In your examples you can use your lists as vector in c++. So if you want to loop over a vector you can do like this:

int cuenta_pares(vector <int> numeros):
    int cuenta{0};
    for(numero{0};numero<numeros.size();numero++){
        if(numero % 2 == 0){
            cuenta += 1
        }
    }
    return cuenta

for using vector in c++ you must include #include

Here I let a website for reference

enter link description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM