Ir ao conteúdo
  • Cadastre-se

Dúvida simples sobre o loop "for".


claudiogc

Posts recomendados

Boa noite!

Digamos que eu tenha uma lista de objetos, como no código abaixo(sei que no exemplo é de inteiros), uma lista grande, não só de tamanho cinco, como no exemplo1. No caso do loop "for", não seria melhor eu declarar uma variável
"tamanho" e armazenar nela o tamanho da lista ao invés de colocar o "lista.size( )" na condicional do loop, como no exemplo2? Eu imagino que do jeito que está no exemplo1, a cada ciclo ele vai ter que calcular o tamanho da lista, já no exemplo2 o programa só calculará uma vez e depois fará a comparação com um valor fixo. Sendo assim o exemplo2 não é mais eficiente que o exemplo1?

#include <iostream>#include <list>using namespace std;int main( ){    list<int> lista(5, 0);    for(int i = 0; i < lista.size( ); i++)        //qualquer coisa aqui            return 0;}
#include <iostream>#include <list>using namespace std;int main( ){    list<int> lista(5, 0);    int tamanho = lista.size( );    for(int i = 0; i < tamanho; i++)        //qualquer coisa aqui            return 0;}

Obrigado!
Link para o comentário
Compartilhar em outros sites

Sempre me perguntei como o programador fez a classe vector(ou a classe list). Creio eu que na época como eles pensavam bastante em tempo, e eficiência do código,

acho que a classe foi implementada assim:

namespace std{    class vector<T>    {        private:           int size;           // demais variaveis..        public:           inline int size();           void push_back(T item);           void remove(int id);           void clear();           //demais métodos..    };    inline vector<T>::size()    {        return size;    }    vector<T>::push_back(T item)    {        //insere o item na lista        //...        size++;//incrementa o tamanho da lista.    }    vector<T>::remove(int id)    {       //remove o item da lista       //...       size--;//diminue em 1 o tamanho da lista    }     vector<T>::clear()    {       //remove todos os itens da lista       //...       size = 0;    }}

É uma ideia de como foi implementado, e se for assim não há problema em chamar o size() diretamente, até por que ele é inline. Creio eu que não há diferença de performance.

Link para o comentário
Compartilhar em outros sites

	template<class _Iter>		void _BConstruct(_Iter _First, _Iter _Last)		{	// initialize from [_First, _Last), input iterators		insert(begin(), _First, _Last);		}	vector(_Myt&& _Right)		: _Mybase(_STD forward<_Myt>(_Right))		{	// move construct by moving _Right		}	vector(_Myt&& _Right, const _Alloc& _Al)		: _Mybase(_STD forward<_Myt>(_Right), _Al)		{	// move construct by moving _Right, allocator		}	_Myt& operator=(_Myt&& _Right)		{	// assign by moving _Right		if (this != &_Right)			{	// different, assign it			clear();			if (_Alty::propagate_on_container_move_assignment::value				&& this->get_allocator() != _Right.get_allocator())				{	// assign vector, dumping proxy				this->_Free_proxy();				this->_Myvec = _STD move(_Right._Myvec);				this->_Alloc_proxy();				}			else				this->_Myvec = _STD move(_Right._Myvec);			this->_Mysize = _Right._Mysize;			_Right._Mysize = 0;			}		return (*this);		}	vector(_XSTD initializer_list<bool> _Ilist,			const _Alloc& _Al = allocator_type())		: _Mybase(0, false, _Al)		{	// construct from initializer_list		insert(begin(), _Ilist.begin(), _Ilist.end());		}	_Myt& operator=(_XSTD initializer_list<bool> _Ilist)		{	// assign initializer_list		assign(_Ilist.begin(), _Ilist.end());		return (*this);		}	void assign(_XSTD initializer_list<bool> _Ilist)		{	// assign initializer_list		assign(_Ilist.begin(), _Ilist.end());		}	iterator insert(const_iterator _Where,			_XSTD initializer_list<bool> _Ilist)		{	// insert initializer_list		return (insert(_Where, _Ilist.begin(), _Ilist.end()));		}	~vector() _NOEXCEPT		{	// destroy the object		this->_Mysize = 0;		}	_Myt& operator=(const _Myt& _Right)		{	// assign from _Right		this->_Mysize = _Right._Mysize;		this->_Myvec = _Right._Myvec;		return (*this);		}	void reserve(size_type _Count)		{	// determine new minimum length of allocated storage		this->_Myvec.reserve(this->_Nw(_Count));		}	size_type capacity() const _NOEXCEPT		{	// return current length of allocated storage		return (this->_Myvec.capacity() * _VBITS);		}	iterator begin() _NOEXCEPT		{	// return iterator for beginning of mutable sequence		return (iterator((_Vbase *)this->_Myvec._Myfirst, this));		}	const_iterator begin() const _NOEXCEPT		{	// return iterator for beginning of nonmutable sequence		return (const_iterator((_Vbase *)this->_Myvec._Myfirst, this));		}	iterator end() _NOEXCEPT		{	// return iterator for end of mutable sequence		iterator _Tmp = begin();		if (0 < this->_Mysize)			_Tmp += this->_Mysize;		return (_Tmp);		}	const_iterator end() const _NOEXCEPT		{	// return iterator for end of nonmutable sequence		const_iterator _Tmp = begin();		if (0 < this->_Mysize)			_Tmp += this->_Mysize;		return (_Tmp);		}	const_iterator cbegin() const _NOEXCEPT		{	// return iterator for beginning of nonmutable sequence		return (((const _Myt *)this)->begin());		}	const_iterator cend() const _NOEXCEPT		{	// return iterator for end of nonmutable sequence		return (((const _Myt *)this)->end());		}	const_reverse_iterator crbegin() const _NOEXCEPT		{	// return iterator for beginning of reversed nonmutable sequence		return (((const _Myt *)this)->rbegin());		}	const_reverse_iterator crend() const _NOEXCEPT		{	// return iterator for end of reversed nonmutable sequence		return (((const _Myt *)this)->rend());		}	void shrink_to_fit()		{	// reduce capacity		if (this->_Myvec._Has_unused_capacity())			{	// worth shrinking, do it			_Myt _Tmp(*this);			swap(_Tmp);			}		}	iterator _Make_iter(const_iterator _Where)		{	// make iterator from const_iterator		iterator _Tmp = begin();		if (0 < this->_Mysize)			_Tmp += _Where - begin();		return (_Tmp);		}	reverse_iterator rbegin() _NOEXCEPT		{	// return iterator for beginning of reversed mutable sequence		return (reverse_iterator(end()));		}	const_reverse_iterator rbegin() const _NOEXCEPT		{	// return iterator for beginning of reversed nonmutable sequence		return (const_reverse_iterator(end()));		}	reverse_iterator rend() _NOEXCEPT		{	// return iterator for end of reversed mutable sequence		return (reverse_iterator(begin()));		}	const_reverse_iterator rend() const _NOEXCEPT		{	// return iterator for end of reversed nonmutable sequence		return (const_reverse_iterator(begin()));		}	void resize(size_type _Newsize, bool _Val = false)		{	// determine new length, padding with _Val elements as needed		if (size() < _Newsize)			_Insert_n(end(), _Newsize - size(), _Val);		else if (_Newsize < size())			erase(begin() + _Newsize, end());		}	size_type size() const _NOEXCEPT		{	// return length of sequence		return (this->_Mysize);		}

se abrir o cabeçário vector.h verá o seguinte trecho de código acima, o último método - size() é declarado e implementado dentro da classe _Iter classe base da classe vector e list,

sendo portanto inline. Isso prova que não perde performance pois o método é reescrito no local de chamado sendo inline.

Link para o comentário
Compartilhar em outros sites

Visitante
Este tópico está impedido de receber novas respostas.

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

Ebook grátis: Aprenda a ler resistores e capacitores!

EBOOK GRÁTIS!

CLIQUE AQUI E BAIXE AGORA MESMO!