0

Why do I get the error "vector iterators incompatible" when I want to run the function "klimaTag()"? I want to give it the iterator of the vector temperatures. How can I do that? I only want to loop over the vector in the main function.

#include <iostream>
#include <vector>

class TemperatureCalculator {
private:
    std::vector<float> temperatures;

public:
    TemperatureCalculator(std::vector<float> temperatures) {
        this->temperatures = temperatures;
    }

    std::string klimaTag(std::vector<float>::iterator i) {
        if (*i >= 25 and *i < 30) {
            return "Sommertag";
        }
        else if (*i >= 30 and *i < 35) {
            return "Heißer Tag";
        }
        else if (*i >= 35) {
            return "Wüstentag";
        }
        else {
            return "Normaltag";
        }
    }

    void get_user_input() {
        int numberDays;
        std::cout << "Wie viele Tage möchten Sie auswerten?" << std::endl;
        std::cin >> numberDays;

        float current_temp;

        for (int i = 0; i < numberDays; i++) {
            std::cout << "Hoechsttemp für Tag " << i + 1 << " eingeben: ";
            std::cin >> current_temp;
            temperatures.push_back(current_temp);
        }
    }

    std::vector<float> get_temperature() {
        return this->temperatures;
    }

};

int main()
{
    TemperatureCalculator t({});
    t.get_user_input();

    for (std::vector<float>::iterator i = t.get_temperature().begin(); i != t.get_temperature().end(); i++) {
        std::cout << "Tag " << *i + 1 << " ist ein " << t.klimaTag(i) << std::endl;
    }
}
dennis
  • 15
  • 2

1 Answers1

0

You return copy of vector in get_temperature, and so use iterator of temporary vector in

std::vector<float>::iterator i = t.get_temperature().begin()

Solution is to return reference:

class TemperatureCalculator {
private:
    std::vector<float> temperatures;

// ...
public:
    const std::vector<float>& get_temperature() const { return this->temperatures; }
    // Possibly:
    //std::vector<float>& get_temperature() { return this->temperatures; }
};

Notice that passing simple iterator seems strange whereas passing value do the job:

std::string klimaTag(float f) const
{
    if (25 <= f and f < 30) {
        return "Sommertag";
    }
    else if (30 <= f and f < 35) {
        return "Heißer Tag";
    }
    else if (*35 <= f) {
        return "Wüstentag";
    }
    else {
        return "Normaltag";
    }
}

and so your loop becomes:

for (float f : t.get_temperature()) {
    std::cout << "Tag " << f + 1 << " ist ein " << t.klimaTag(f) << std::endl;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302