Lepo ispisivanje kontejnera
Napisati funkciju:
template <typename Container>
void print_container(const Container& c,
const std::string& separator = " ",
std::ostream& os = std::cout);koja ispisuje elemente kontejnera c na izlazni tok os, razdvojene stringom separator. Na početku i na kraju ispisa treba ispisati uglaste zagrade [ i ]. Ako je kontejner prazan, treba ispisati samo zagrade.
Test
main.cpp
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <list>
namespace matf {
template <typename Container>
void print_container(const Container& c,
const std::string& separator = " ",
std::ostream& os = std::cout)
{
// Ovde ide vaša implementacija
}
} // namespace matf
int main(void)
{
std::vector<int> vec = {1, 2, 3, 4, 5};
matf::print_container(vec, ", "); // Output: [ 1, 2, 3, 4, 5 ]
std::vector<std::string> str_vec = {"apple", "banana", "cherry"};
matf::print_container(str_vec, " - "); // Output: [ apple - banana - cherry ]
std::vector<double> empty_vec;
matf::print_container(empty_vec); // Output: []
std::vector<char> char_vec = {'A', 'B', 'C'};
matf::print_container(char_vec, "|", std::cerr); // Output: [ A|B|C ] to std::cerr
std::set<std::string> str_set = {"dog", "cat", "bird"};
matf::print_container(str_set); // Output: [ bird cat dog ]
std::list<float> float_list = {1.1f, 2.2f, 3.3f};
matf::print_container(float_list, "; "); // Output: [ 1.1; 2.2; 3.3 ]
return 0;
}cout
[ 1, 2, 3, 4, 5 ]
[ apple - banana - cherry ]
[]
[ A|B|C ]
[ bird cat dog ]
[ 1.1; 2.2; 3.3 ]
Rešenje
main.cpp
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <list>
namespace matf {
template <typename Container>
void print_container(const Container& c,
const std::string& separator = " ",
std::ostream& os = std::cout) {
if (c.empty()) {
os << "[]" << std::endl;
return;
}
os << "[ ";
for (auto it = c.begin(); it != c.end(); ++it) {
os << *it;
if (std::next(it) != c.end()) {
os << separator;
}
}
os << " ]" << std::endl;
}
} // namespace matf
int main(void)
{
std::vector<int> vec = {1, 2, 3, 4, 5};
matf::print_container(vec, ", "); // Output: [ 1, 2, 3, 4, 5 ]
std::vector<std::string> str_vec = {"apple", "banana", "cherry"};
matf::print_container(str_vec, " - "); // Output: [ apple - banana - cherry ]
std::vector<double> empty_vec;
matf::print_container(empty_vec); // Output: []
std::vector<char> char_vec = {'A', 'B', 'C'};
matf::print_container(char_vec, "|", std::cerr); // Output: [ A|B|C ] to std::cerr
std::set<std::string> str_set = {"dog", "cat", "bird"};
matf::print_container(str_set); // Output: [ bird cat dog ]
std::list<float> float_list = {1.1f, 2.2f, 3.3f};
matf::print_container(float_list, "; "); // Output: [ 1.1; 2.2; 3.3 ]
return 0;
}