C++ efficient container-Vector-design

C++ efficient container-Vector-design

Note: I am original, if you find similarities, you will be responsible for the consequences

Note that C++ 17 will be used to implement

Compare STL containers

Although STL containers are very efficient (speed), they also have flaws

STL defect

1-The following syntax cannot be used

#include <iostream>
#include <vector>

// 示例
void show_container(const std::vector<int>& container)
{
    
    
	std::cout << "Vector { ";
	for (int val : container)
	{
    
    
		std::cout << val << ", ";
	}
	
	std::cout << '}';
}

struct my_custom_allocator : public std::allocator<int> {
    
    };

int main(void)
{
    
    
	std::vector<int, my_custom_allocator> vec;
	
	show_container(vec); // 错误, 不同的模板参数
	
	(void)getchar();
	return 0;
}

Of course we can write like this

#include <iostream>
#include <vector>

// 示例
template <typename Alloc>
void show_container(const std::vector<int, Alloc>& container)
{
    
    
	std::cout << "Vector { ";
	for (int val : container)
	{
    
    
		std::cout << val << ", ";
	}
	
	std::cout << '}';
}

struct my_custom_allocator : public std::allocator<int> {
    
    };

int main(void)
{
    
    
	std::vector<int, my_custom_allocator> vec;
	
	show_container(vec); // 可以正常编译
	
	(void)getchar();
	return 0;
}

But doing so will inflate the code and the executable file will become larger (small projects have little impact).

2-Implicit sharing is not supported

Note that this is not the original intention of the STL design container, but it can improve performance

#include <iostream>
#include <vector>

int main(void)
{
    
    
	std::vector<int> container_1;
	std::vector<int> container_2 = container_1;
	// 上面这段代码会进行拷贝, 要是是大小很大的vector就要拷贝很久
	// 要是它们可以共享数据就可以减少不必要的拷贝
	
	(void)getchar();
	return 0;
}

3-Different compilers implement different

This is uncomfortable, those who implement poorly will slow down the program

Advantages of STL

Advantages: The designed STL is fast and cross-platform (after all, it is a standard library)

Design your own container

demand

  1. Cannot specify a custom allocator (allocator)
  2. Implicit sharing
  3. More convenient operation
  4. Use type_traits in template metaprogramming for optimization

Implement the underlying code of Vector in the next issue.

Next: C++ Efficient Container-Vector-Implementing the Low Level-Reference Counting Class

Guess you like

Origin blog.csdn.net/m0_47534090/article/details/108634156