Skip to content

Instantly share code, notes, and snippets.

@ProfAndreaPollini
Created January 8, 2025 08:21
Show Gist options
  • Save ProfAndreaPollini/4d072467d647f50b957bcf79a5321e99 to your computer and use it in GitHub Desktop.
Save ProfAndreaPollini/4d072467d647f50b957bcf79a5321e99 to your computer and use it in GitHub Desktop.
operazioni su vettori e array ( anche con std::optional)
#include <iostream>
#include <vector>
#include <optional>
bool esiste(const std::vector<int>& v,int value) {
for(auto i =0; i < v.size(); i++) {
if (v[i] == value) {
return true;
}
}
return false;
}
std::optional<int> primo_elemento_pari(const std::vector<int>& v) {
for(auto i = 0; i < v.size(); i++) {
if(v[i] %777 == 0) {
return v[i];
}
}
return std::nullopt;
}
int pos_primo_elemento_pari(const std::vector<int>& v) {
for(auto i = 0; i < v.size(); i++) {
if(v[i] %2 == 0) {
return i;
}
}
return -1;
}
int conta_pari(const std::vector<int>& v) {
int n_pari = 0;
for(auto i = 0; i < v.size(); i++) {
if(v[i] %2 == 0) {
n_pari++;
}
}
return n_pari;
}
std::vector<int> elementi_pari(const std::vector<int>& v) {
std::vector<int> ret;
for(auto i = 0; i < v.size(); i++) {
if(v[i] %2 == 0) {
ret.push_back(v[i]);
}
}
return ret;
}
std::vector<int> raddoppia_valori(const std::vector<int>& v) {
std::vector<int> ret;
for(auto i = 0; i < v.size(); i++) {
auto y = v[i]*2;
ret.push_back(y);
}
return ret;
}
int main() {
std::vector<int> valori{1,4,5,6,7,3,5};
auto a = esiste(valori,3);
auto b = primo_elemento_pari(valori);
if (b.has_value()) {
std::cout << b.value() << std::endl;
} else {
std::cout << "nessun valore" << std::endl;
}
auto c = pos_primo_elemento_pari(valori);
auto e = elementi_pari(valori);
auto d = conta_pari(valori);
auto f = raddoppia_valori(valori);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment