Skip to content

Instantly share code, notes, and snippets.

@colesnicov
Last active November 17, 2024 16:03
Show Gist options
  • Save colesnicov/fbea3cc0c54159a399105dd1ee57eae7 to your computer and use it in GitHub Desktop.
Save colesnicov/fbea3cc0c54159a399105dd1ee57eae7 to your computer and use it in GitHub Desktop.
C++ Tips

Tipy a triky s std::vector

Odstraneni prvku

Spravna cesta jak odstranit prvek z vectoru..

int num_to_delete = 2;
std::vector<int> vec { 1, 2, 5, 3, 8, 4 };
std::vector<int>::iterator it;
for (it = vec.begin(); it != vec.end(); it++)
{
	printf("vec value: %d/%ul\n", *it, vec.size());

	if (num_to_delete == *it)
	{
	    printf("erase vec value: %d/%ul\n", *it, vec.size());
	    
	    /// Musi se prevzit ukazatel na novy prvek v iteratoru,
	    /// ktery nasledoval za odstranenym prvkem.
	    /// I kdyz zakomentovany radek nize funguje, zda se bez problemu,
	    /// je lepsi to udelat tak jak se to patri..
	    // vec.erase(it);
	    
	    /// Takto se musi mazat, metoda `erase` vraci ukazatel na obnoveny iterator..
	    it = vec.erase(it);
	    
	    /// Pokud mazu jen jeden prvek, muzu ukoncit cykl, nebo pokracovat ve vypisu..
	    /// Pro ukonceni cyklu, odkomentuj nasledujici radek..
	    // break;
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment