Vectors

I need to make this code work with vectors? How can I do it ?

Last edited on
I don't get it. Your code compiles fine and works , What does it do ? What help do you need specifically ?
Please post your comments and other strings in English.(ofc , we can use Google Translate but save us some time.)
Also , provide an "input.txt" file.
i'm not sure if it is working with vectors :( i have a file containing conrdinates, each line contain a couple(x, z), i need to get the point with the minimum value of z, using vectors?

Last edited on
But what do you think doesn't work? It should be pretty easy to see if it works or not given this input data, so I'm not quite sure what you mean when you say "I'm not sure it works with vectors". As far as I can see you are using vectors.
You did most of it correctly , except some small logic errors , and the misuse of for-each loop.
Here's the code , after a little editing and indenting.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <fstream>
#include <iomanip> 
#include <vector>

using namespace std;

int main()
{
	std::vector<float> mes_x,mes_z;
	ifstream fin;
	fin.open("input.txt");
	for(int i = 0; i < 50; ++i) 
	{
		float x,z;
		fin >> x >> z;
		mes_x.push_back(x); 
		mes_z.push_back(z);
		//Display the point
		cout << " Point no. " << i << " = {" << x << "," << z << "}" << endl;
	}
	float min = mes_z[0];//set min to mes_z[0],this way its more general
	int a=0;//the point which has the min. value for z.
	//here a for-each loop may a little inconvenient
	for(int i = 0; i < 50 ; ++i)
	{
		if(mes_z[i] < min)//An if statement should be used here,not a while loop
		{
			min = mes_z[i];
			a = i;
		}
	}
	//Display the point with the minimum value
	cout << "\nThe point with the minimum value : " << a << endl; 
	//fin.close(); , unnecessary , the destructor does it for you : RAII
    return 0;
}

Hope that helps.
Last edited on
That still has logical issues.

Line 13. Do not trust that the file has 50 records. Read what there is. You can have an additional "up to" limit though.

Line 16. Do not trust that a read succeeds. Test it.
1
2
3
4
5
6
float x, z;
while ( fin >> x >> z ) {
  mes_x.push_back(x);
  mes_z.push_back(z);
  cout << " Point no. " << mes_x.size() << " = {" << x << "," << z << "}\n";
}

Lines 22 and 25. Do not trust that the vector(s) have any or particularly 50 elements. Someone could change the first loop and forget to edit this. Vector knows its size.

Without a counter:
1
2
3
4
5
6
if ( 0 < mes_x.size() && mes_x.size() == mes_z.size() ) {
  auto low = std::min_element( begin(mes_z), end(mes_z) );
  auto pos = std::distance( begin(mes_z), low );
  cout << "\nThe point with the minimum value : " << 1+pos
       << " = {" << mes_x[pos] << "," << *low << "}\n";
}

Topic archived. No new replies allowed.