How does C++ list<T> act on inserting elements? -


i have question regarding c++ lists. below code don't quite understand.

#include <iostream> #include <list> #include <string> using namespace std;  struct customer { string firstname; string lastname; };  void replace(list<customer>& customers, int index, customer item) { std::list<customer>::iterator = customers.begin(); advance(it, index); *it = item; }  customer (list<customer>& customers, int index) { std::list<customer>::iterator = customers.begin(); advance(it, index); return *it; }  int main() {  list<customer> customers; customer c1; c1.firstname = "jack"; c1.lastname = "smith"; customer c2; c2.firstname = "jane"; c2.lastname = "doe";  insert(customers, 50, c1);  cout << get(customers,0).firstname << endl; //outputs jack though inserted @ index 50  insert(customers, 49, c2);  cout << get(customers,0).firstname << endl; //outputs jane  cout << get(customers,50).firstname << endl; //where did jack go?  return 0; } 

i'm using eclipse c++ , gcc. questions are:

1 - why doesn't example crash i'm inserting items straight off @ index 50?

2 - happens spots @ indexes 0 - 49?

3 - in insert() , get() methods correct check index size of list , make sure don't pass list boundaries?

why doesn't example crash i'm inserting items straight off @ index 50?

because undefined behaviour doesn't cause crash.

you not inserting @ index 50. you're taking past-the-end iterator (which can't incremented), attempting increment 50 times; leaping further undefined behaviour dereferencing thoroughly invalid iterator end with.

the gnu library implements list circular list, dummy node act "past end" position. so, in implementation, incrementing off-the-end iterator return start of list, , dereferencing lead accessible memory, there won't crash. write dummy element, overwrite it.

other implementations may behave differently when perform invalid operations.

what happens spots @ indexes 0 - 49?

they don't exist, since never put in list.

in insert() , get() methods correct check index size of list , make sure don't pass list boundaries?

yes. advance won't check end of sequence, since has no way of knowing is. you'll undefined behaviour if try advance beyond end, it's check first.


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -