Structure and vector help pls!

Hi, I have a small problem when I use push_back to save a structure in a vector, the last value is repeated.
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
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
//#include "point.h"
using namespace std;
/*#ifndef COORDENADA_H 
#define COORDENADA_H*/
struct point{
private:
	float x=0.0,y=0.0;
public:
	void generate(point &,vector<point> &);
	void view(vector<point> &);
};
//#endif 

int main(){
	vector<point> save;
	point C2D;
	C2D.generate(C2D,save);
	C2D.view(save);
	return 0;
}

void point::generate(point & a,vector<point> & s){
	
	int n=0,i=0;
	
	while(n<2 || n>100){
		cout<<"[2-100]: ";cin>>n;
	}
	
	while(i<n){	
		x=(int)rand()%10;y=(int)rand()%10;	
		cout<<"("<<x<<" , "<<y<<")"<<endl;
		s.push_back(a);
		i++;
                
	}cout<<endl;
}

	void point::view (vector<point> & s){
		for(auto & a : s) {
		cout<<"("<<x<<" , "<<y<<")"<<endl;
		}
	}


example: when I place 4 I can see
1
2
3
4
5
6
7
8
9
10
11
//generate(C2D,save) 	
[2-100]: 4
(3 , 6)
(7 , 5)
(3 , 5)
(6 , 2)

(6 , 2)
(6 , 2)
(6 , 2)
(6 , 2)


Last edited on
1
2
3
x=(int)rand()%10;y=(int)rand()%10;	
cout<<"("<<x<<" , "<<y<<")"<<endl;
s.push_back(a);

If I'm reading this correctly, you generate and display this->x and this->y, but then you push_back an unrelated value, a.

In other words, where you ever assign values for a?

Btw, don't bother translating your code, it just makes it not compilable...
Last edited on
Sorry I am new in this just observed that you can run the code here.
I was working on a project, I did not know how to put it.
Last edited on
Change auto point
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
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
//#include "point.h"
using namespace std;
/*#ifndef COORDENADA_H 
#define COORDENADA_H*/
struct point{
private:
	float x=0.0,y=0.0;
public:
	void generate(point &,vector<point> &);
	void view(vector<point> &);
};
//#endif 

int main(){
	vector<point> save;
	point C2D;
	C2D.generate(C2D,save);
	C2D.view(save);
	return 0;
}

void point::generate(point & a,vector<point> & s){
	
	int n=0,i=0;
	
	while(n<2 || n>100){
		cout<<"[2-100]: ";cin>>n;
	}
	
	while(i<n){	
		x=(int)rand()%10;y=(int)rand()%10;	
		cout<<"("<<x<<" , "<<y<<")"<<endl;
		s.push_back(a);
		i++;
		
	}cout<<endl;
}

void point::view (vector<point> & s){
	for(point &a : s) {
		cout<<"("<<a.x<<" , "<<a.y<<")"<<endl;
	}
}
Topic archived. No new replies allowed.