How to write a function that accepts a std :: vector or std :: list?

A bit of a simple question, I think.

Vectors and lists have push and pop functions, and, more importantly, you can repeat:

for ( auto value : items ) ... 
Nonetheless,

std :: vector and std :: list do not have a common class. Therefore, the question arises: how to write a function that will take one (or, really, something else that corresponds to the implementation)?

 std::list<int> a; std::vector<int> b; DoSomething(a); DoSomething(b); 

I would like to do this without overload. If templates are used, they should not cause crazy error messages. For example, the following code is

 int a; DoSomething(a); 

- should lead to a compilation error on the call site, not inside the template!

Does anyone have any ideas?

+4
source share
2 answers

The C ++ Standardization Committee tried to introduce the concepts of C ++ 0x (now C ++ 11) to solve the problems you are raising here. They were forced to support them at the end, so we have to wait until the next version of the standard.

Boost BCCL offers a portable temporary solution. I have never used a library, so I cannot vouch for it or against it.

+1
source

Most stl algorithms use iterators as an abstraction layer from a container.

For example, sort takes 2 random access iterators to sort:

 template <class RandomAccessIterator> void sort (RandomAccessIterator first, RandomAccessIterator last); 

Most algorithms can be implemented using this idiom.

Depending on the algorithm you plan to implement, you will need to choose between 4 types of standard iterators

Here is a link that explains which type is best suited

0
source

Source: https://habr.com/ru/post/1488608/


All Articles