The C++ Standard Template Library has a decent set of containers. std::array, std::vector, std::list, ...
When you write a software function, it can be useful to handle whatever container the user wishes to use.
In my little print function here , the logic can accept a rich set of std::string containers (and container ranges / views). It will call the stream operator of each element within the string.
#include <vector>
#include <array>
#include <string>
#include <ranges>
#include <iostream>
std::array <std::string, 2> a = {"arr", "ay"};
std::vector <std::string> v = {"vec", "tor"};
void print(const auto& range) {
for (const auto& r: range) {
std::cout << r;
}
std::cout << std::endl;
}
int main() {
print(a);
print(v);
auto r_a = std::views::all(a);
auto r_v = std::views::all(v);
print(r_a);
print(r_v);
return 0;
}
In this code, 4 containers and views are tested:
- std::array<std::string, 2>: arrays have a fixed length
- std::vector<std::string>: vectors have dynamic length
- view over the array (in this case, a view that just contains all its elements)
- view over the vector (in this case, a view that just contains all its elements)
All 4 can be handled by the function. If my function would try to perform an action that either the container, or the std::string within, can't handle, you get a compile time error.
Output:
arrayvectorarrayvector
If you wonder why I used the const and & constructs, or put the word contains in italics, ask. If you know, comment.
note: if you want to use methods or functions with auto parameters in a library, you have to include the implementation in the header file. That's similar to using templates (that are akin to auto).
Thanks for reading.
Link to all posts.