Witam, mam problem bo musze napisać kod a nie wiem jak ma on wyglądać i jak się do niego zabrać. Treść zadania:
Napisz wzorzec funkcji licz w dowolnym kontenerze sekwencyjnym zawierającym liczby dowolnego typu. Zliczy i zwróci ilość wystąpień konkretnej wartości podanej w argumencie tej funkcji. Gdy kontener jest pusty zostanie wyrzucony wyjątek const*char "No values".
Np. int[]={-1,12,22,12};
vector<int>w(t,t+4);
cout<<int(w,13)<<endl; //zwróci 2
0
0
No i z czym dokładnie masz problem? Masz przecież jasno napisane co ta funkcja ma robić.
0
Jak stworzyć funkcje która będzie zawierała liczby dowolnego typu?
0
Wykorzystaj szablony.
0
początek to będzie
template<typename a, typename b>
void licz (a,b)
ale nie rozumiem o co chodzi z tym kontenerem i jak to zapisać :(
0
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
int licz (vector<T> container, T element){
int counter = 0;
for(auto x : container){
if(x==element){
counter++;
}
}
return counter;
}
int main() {
vector<int> v1 = {1,2,3,4,4,4};
cout<<licz(v1, 4)<<endl;
vector<double> v2 = {1.1, 1.2, 1.3, 1.1};
cout<<licz(v2, 1.1)<<endl;
return 0;
}
0
Dziękuję bardzo ale dlaczego ten kod nie działa?
0
Ciekawe pytanie biorąc pod uwagę że dałem link do ideone które kompiluje i uruchamia ten kod i widać że działa.
1
#include <iostream>
#include <algorithm>
#include <array>
#include <deque>
#include <list>
#include <string>
#include <vector>
template<typename T, typename E>
int foo(T const& container, E element)
{
return std::count(std::begin(container), std::end(container), element);
}
int main()
{
std::cout << foo(std::array<double, 5>{ 1, 2, 2, 3, 2 }, 0) << std::endl;
std::cout << foo(std::deque<double>{ 1, 2, 2, 3, 2 }, 1) << std::endl;
std::cout << foo(std::list<double>{ 1, 2, 2, 3, 2 }, 2) << std::endl;
std::cout << foo(std::string { '1', '2', '2', '3', '2' }, '3') << std::endl;
std::cout << foo(std::vector<double>{ 1, 2, 2, 3, 2 }, 4) << std::endl;
return 0;
}