Pointer error in vector

The error is "delete (*it)".

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
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
	vector<string> vList;


	vList.push_back("a");
	vList.push_back("b");
	vList.push_back("c");
	vList.push_back(":");
	vList.push_back(":");
	vList.push_back(":");
	vList.push_back("d");


		std::string sswicher, str2;
	char lastChar1, lastChar2;
	bool blok1 = false;
	for(auto it = vList.begin(); it != vList.end(); it++)
	{
		if(blok1 == false){
			sswicher = (*it);
			lastChar1 = *sswicher.rbegin();
		}
			blok1 = false;	

			it++;
			sswicher = (*it);
			lastChar2 = *sswicher.rbegin();

			if((lastChar1 == ':') && (lastChar2 == ':'))
			{
				it-=1;
				delete (*it); //Expression has to be a pointer <-- What should I do now?
				(*it) = nullptr;
				it = vList.erase(it);
				lastChar1 = lastChar2;
				blok1 = true;
			}	
	}

	for(auto it = vList.begin(); it != vList.end(); it++)
	{
		cout << (*it) << endl;
	}


getchar();
return 0;
}

Thanks for any cooperation!
Last edited on
delete is meant to be used on pointers to delete memory that was allocated using new. *it is not a pointer, it's a std::string, and you didn't use new to create it so delete is not what you should be using here.

On line 38 you remove the string from the vector. You don't need to do more than that.

Note that after line 38 it will refer to the element after the removed element and then on line 21 it will be stepped once again so the loop misses to handle the element after the removed one. To avoid this you should make sure that it++ is only executed if the previous element was not removed, something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
for(auto it = vList.begin(); it != vList.end();)
{
	...
	if(...)
	{
		...
		it = vList.erase(it);
		...
	}
	else
	{
		it++;
	}
}
Topic archived. No new replies allowed.