Hi friends,

I have 3 different vectors, V1, V2 and V3. V1 and V2 have the same size and each line refers the same record. I would like to write a function that get each line from V3 and check if exists in V2, and if is == "M" in V1.

I tried but I found some errors.

Can you help me?

Cheers,

Sads

V1 V2
M 150
M 152
M 160
M 170
F 190
F 200
M 250

V3
188
160
200
250

string pesqM(vector<string> &V2, vector<string> &V1, vector<string> &V3)
 {
	    for(int a = 0; a < V1.size(); a++)
	    {
	    	if (V1[a] == "M")
	    	{
	    		cout << "\nPosition: " << a + 1 << endl;
	    		cout << "ID: " << V2[a] << endl;

	    		// Here start the error
			vector<string>::iterator it;
         		iterator to vector element:
	    		it = find(V3.begin(), V3.end(), V2[a]);
	    		cout << "The element is " << *it << endl;
	    	}
	    }
		return ("PM");

What errors?

Hi Agni,

I had problems with memory ... I don't know if the code is correct.

I hope that are problems when I used "it".

Cheers,

Sads

That sounds very abstract for anyone to help you. How do you know you have memory issues? I can't make out any memory issues from the code snipped you have given here. You should though check if your iterator points to end() before you dereference it.

Hi Agni,

I changed all and now I'm trying use this code:

string pesqM(vector<string> &V2, vector<string> &V1, vector<string> &V3)
 {

	 for(int a = 0; a < V3.size();a++)
		 for(int b = 0; b < V2.size();b++)
		 {
			
			 if (strcmp(V1[b].c_str(),"M") == 0 && V3[a]==V2[b]) // I tried before if(V1[b]=="M" && V3[a] == v2[b])
 	    	{
 	    		cout << "ID : " << V2[b] << endl;
 	    	}
			else
			{
				cout << "Not found! " << endl;
			}
		 }

	    		return ("PM");
 }

Every time is going outside the if and ran the else. I tried 2 different comparisons ... Can you help in this IF-ELSE comparing vector[pos] = "M"?

I found a problem in V3[a] == v2. The both are 150 for example but the first one is "150" and the second one is "150 ". How can I remove the white spaces from each line in a vector?

Look at string class reference at string cpp. The functions find and erase might be helpful in finding a whitespace and then erasing the character at that location.

Hi Agni,

I decided to use this function. Thanks for your help!

Cheers,

Sads.

string removeWhite (std::string &str)
{
	std::string temp;
	    for (unsigned int i = 0; i < str.length(); i++)
	        if (str[i] != ' ') temp += str[i];
	    str = temp;
	    return str;
}
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.