U++ framework
Do not panic. Ask here before giving up.

Home » U++ Library support » U++ Core » Vector<T>::Set(int i, T&& x) proposal
Vector<T>::Set(int i, T&& x) proposal [message #49119] Tue, 19 December 2017 23:30 Go to previous message
Novo is currently offline  Novo
Messages: 1431
Registered: December 2006
Ultimate Contributor
I propose to add method below to the Vector class.
template <class T>
T& Vector<T>::Set(int i, T&& x) {
	ASSERT(i >= 0);
	const int count = GetCount();
	if (i == count)
		return Add(pick(x));
	else if (i > count) {
		At(i - 1);
		return Add(pick(x));
	}
	
	T* addr = vector + i;
	addr->~T();
	::new(addr) T(pick(x));
	return *addr;
}


Or it can be implemented like this:
template <class T>
T& Vector<T>::Set(int i, T&& x) {
	ASSERT(i >= 0);
	At(i);
	T* addr = vector + i;
	addr->~T();
	::new(addr) T(pick(x));
	return *addr;
}

Second implementation has less memory allocation stuff. It is hard to tell which one is better.
I believe there is no need to check that x is already contained in Vector because it is impossible to get an rvalue of a Vectors's element.


Regards,
Novo
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Function.h: "expression cannot be used as a function"
Next Topic: Core/SSL crashes at exit on Linux.
Goto Forum:
  


Current Time: Sun May 03 22:26:50 GMT+2 2026

Total time taken to generate the page: 0.00702 seconds