Hello everybody. I'm trying to write program with vectors and iterators. Coordinates X and Y are entered from keyboard (as structure) and placed in vector of points. It's necessary to display coordinates with maximal X and Y. This code was compiled but not display maximal X. What should I change?

#include <iostream.h>
#include <conio.h>
#include <vector.h>
#include <math.h>

struct points {
    float x, y;
};

int main()
{
using namespace std;

int i;
int max;

vector<points>pointvect; //vector declaration
points point;

cout << "Enter a dimension of vectors:\n";
cin >> i;

for (int k = 0; k <= i; k++) {
    cout << "Inpurt x\n";
    cin >> point.x;
    cout << "Input y\n";
    cin >> point.y;
}

pointvect.push_back(point); // add point to the vector


// define iterators

vector<points>::iterator itr;
vector<points>::iterator first = pointvect.begin();
vector<points>::iterator end = pointvect.end();

(first)->x = max;

for (itr = first; itr <= end; itr++) {
        if ((itr)->x > max) {
        cout << "Maximal X is: ", (itr)->x;
    }
}
getch();
return 0;
}

Recommended Answers

All 3 Replies

  1. In C++, header files do not need .h (and do not recommend). So remove all of them.
  2. Don't use conio.h. I don't know who taught you that, or what museum you got your book from, but they should have stopped teaching that two decades ago.
  3. By convention, we generally put using namespace std; after all the includes, but before any definitions, so that all functions can benifit from using the namespace directly.
  4. Line 30 needs to be put in the loop to be effective. Otherwise only the last point will be added to the vector.
  5. You don't need to put brackets around everything you use -> on. It makes it a little deceptive to read.
  6. getch() is not part of the C standard. Use getchar(); instead.

getch() is not part of the C standard. Use getchar(); instead.

Why use either one? cin.get() is already in <iostream> so use it instead of adding more C-code to the program.

.

I suggest changing a bit your struct:

struct point {
    float x, y;

    point (float x, float y) {
        this->x = x;
        this->y = y;
    }

    bool operator <(point &p){
        return this->x < p.x && this->y < p.y;   // comparison logic
    }

    friend ostream& operator<<(ostream& os, const point &p) {
        os << "x: " << p.x << ", y: " << p.y;
        return os;
    }
};

So that you could do something like this:

int main()
{
    // code here

    point max(INT_MIN, INT_MIN);

    for (vector<point> :: iterator it = pointvect.begin() ; 
                                    it != pointvect.end() ; 
                                    it++)
    {
        if (max < *it) max = *it;
    }

    cout << "Max point: " << max << endl;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.