Code Optimization.

Could this code be more optimized?

I mean, using maps, I've just started used maps, will a map make the code smaller and having the same search-n-compare functionality?

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "stdafx.h"
#include <cstdlib>
#include <vector>
#include <string>
#include <iostream>

using namespace std;

class ClassA
{
public:
	int id;
	string name;
	ClassA(int id1, string namep): id(id1), name(namep){}
};

vector<ClassA*> datafill(int size)  
//this function starts filling our vector with objects
{

	int id;
	string name = "" ;

	vector<ClassA*> unvector;
	for(int i = 0; i<size; i++)
	{
		
		cout<<"Enter the id-ul:\n ";

		cin >> id;
		  cin.ignore();
		cout<<"Enter the name-ul:\n";

		getline(cin, name);

		cout<<endl;

		unvector.push_back(new ClassA(id, name));
	}
	return unvector;
}

string search(string s, vector<ClassA*> vec) 
//this one only finds the wanted string
{
	int size = vec.size();
	string res = "" ;
	
	for(int i = 0; i<size; i++)
		if(s.compare(vec[i]->name)==0)
		{
			res = "Object found! :)\n";
			cout<<"The Id of the object is: "<<vec[i]->id<<"\n";
			break;
		}
		else
		res = "Objectul does not exist\n";

	return res;		

}



int _tmain(int argc, _TCHAR* argv[])
{
	
	
	vector<ClassA*> unvector =  datafill(3);
	string result = search("Object", unvector);
cout<<result;
			
		for(int i = 0; i<2; i++)
			delete unvector[i];
		cin.get();

	return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int _tmain(int argc, _TCHAR* argv[])
{
	
	
	vector<ClassA*> unvector =  datafill(3);
	string result = search("Object", unvector);
cout<<result;
		
		/* Use this if you need to keep any object/s
		int keep = 0;
		ClassA* keepObj = unvector[ keep ];
		unvector[ keep ] = new ClassA(0,"");
		*/
		
		// vector can empty itself, you don't need to iterate through them
		unvector.clear();
		cin.get();

	return 0;
}
Last edited on
Also if you want the search to be case insensitive then first convert the string to one case then when you iterate just make the other one return the same case for you to compare against ( no need to modify the original string though ) with ==.
Topic archived. No new replies allowed.