David Cameron is to resign as prime minister after the UK voted to leave the European Union in a historic referendum, with his successor in place by October.