Finding the key of a vector.

Hello,

I've been trying to find the key of a vector, but when I try to access the vector with an iterator and try to return a value it complains about "first" or "second" not being a member of the iterator.
I've been googling to find a way to return key values but I only found it for maps, not vectors.

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
// iTreatment and jTreatment are short integers.
// siTreatment and sjTreatment are std::strings.
// treatmentNames is a std::vector<std::string>

void Painter::SetTreatments(HWND hWnd, bool foo, TCHAR* tc)
{
	string s = tc;

	if (foo == 0) 
	{
		siTreatment = s;

		vector<string>::iterator it;
		for (it = treatmentNames.begin(); it != treatmentNames.end(); ++it)
		{
			if ( (*it)->second == siTreatment ) //error line
			{
				iTreatment = (*it)->first; //error line
				break;
			}
		}
	}
	else 
	{
		sjTreatment = s;

		vector<string>::iterator it;
		for (it = treatmentNames.begin(); it != treatmentNames.end(); ++it)
		{
			if ( (*it)->second == sjTreatment ) //error line
			{
				jTreatment = (*it)->first; //error line
				break;
			}
		}
	}

	InvalidateRect(hWnd, NULL, true);
}


Is there any way to find the key of a vector?

~ Rii
When using std::map you can use first and second because the key-value pairs is stored in std::pair that has public data members called first and second. std::vector stores all elements in a contiguous array and doesn't have keys. Well, you could argue that the index is the key but it's not stored anywhere. You should use *it to get the string from the iterator. If you want to calculate the index of the string in the vector you can do that by calculating the distance between it and the first iterator, it - treatmentNames.begin() or std::distance(treatmentNames.begin(), it).
Last edited on
Thank you for your reply Peter!

I misunderstood the vector, thanks for explaning.

I got the code to work with std::distance(treatmentNames.begin(), it) and it returns the correct value!

Once again, thank you so much.

~ Rii
Topic archived. No new replies allowed.