예시 1번
#include <iostream>
#include <vector>
using namespace std;
int main() {
double sum = 0.0;
const int Number_of_entries = 5;
vector<double> numbers(Number_of_entries);
cout << "Please enter " << Number_of_entries << " numbers: ";
for (int i = 0; i < Number_of_entries; i++) {
cin >> numbers[i];
sum += numbers[i];
}
cout << "The average of ";
for (int i = 0; i < Number_of_entries - 1; i++)
cout << numbers[i] << ", ";
cout << numbers[Number_of_entries - 1] << " is "
<< sum / Number_of_entries << '\n';
}
>>>
Please enter 5 numbers:
3
7
344
12
41
The average of 3, 7, 344, 12, 41 is 81.4
예시 2번
int main() {
const int Size = 3;
vector<int> a{ 5,5,5 };
cout << "a contains ";
for (int i = 0; i < Size; i++)
cout << a.at(i) << " ";
cout << '\n';
for (int i = 0; i <= Size; i++)
a.at(i) = 8;
cout << "a contains ";
for (int i = 0; i < Size; i++)
cout << a.at(i) << " ";
cout << '\n';
}
>>>
a contains 5 5 5
a contains 8 8 8
a contains 8 8 8
예시 3번
void print(const vector<int>& v) {
for (int elem : v)
cout << elem << " ";
cout << '\n';
}
int sum(vector<int> v) {
int result = 0;
for (int elem : v)
result += elem;
return result;
}
int main() {
vector<int> list{ 2, 4, 6, 8 };
print(list);
cout << sum(list) << '\n';
int n = list.size();
for (int i = 0; i < n; i++)
list[i] = 0;
print(list);
cout << sum(list) << '\n';
}
>>>
2 4 6 8
20
0 0 0 0
0
예제 3번 : 소수 Prime list
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
void print(const vector& v) {
for (int elem : v)
cout << elem << " ";
cout << '\n';
}
bool is_prime(int n) {
if (n < 2)
return false;
else{
bool result = true;
double r = n, root = sqrt(r);
for (int trial_factor = 2; result && trial_factor
<= root; trial_factor++)
result = (n % trial_factor != 0);
return result;
}
}
vector<int> primes(int begin, int end) {
vector<int> result;
for (int i = begin; i <= end; i++)
if (is_prime(i))
result.push_back(i);
return result;
}
int main() {
int low, high;
cout << "Please enter lowest and highest values in the range";
cin >> low >> high;
vector prime_list = primes(low, high);
print(prime_list);
}
>>>
Please enter lowest and highest values in the range
1
100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
'Code > C++' 카테고리의 다른 글
[C++] Vector Matrix (0) | 2019.10.18 |
---|---|
[C++] Array / Dynamic array/ static array (0) | 2019.10.18 |
[C++] (example) & operator / pointer / pass by address/ function pointer (0) | 2019.10.17 |
[C++] Vector / (0) | 2019.10.09 |
[C++] & operator / pointer / pass by address/ function pointer (0) | 2019.10.09 |