some changes in chapter06 examples

This commit is contained in:
davoudn 2024-04-09 12:06:48 +03:30
parent 04dea59a6a
commit 89880f6615
5 changed files with 38 additions and 18 deletions

7
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,7 @@
{
"files.associations": {
"format": "cpp",
"span": "cpp",
"string_span": "cpp"
}
}

Binary file not shown.

View File

@ -1,36 +1,49 @@
// fig06_01.cpp
// Initializing an array's elements to zeros and printing the array.
#include <format> // C++20: This will be #include <format>
//#include <../libraries/fmt/include/format.h> // C++20: This will be #include <format>
#include <iostream>
#include <array>
#include <vector>
#include <string>
template <typename T>
void printArray(T& a, std::string tag){
std::cout << "Element Value ---> "<<tag <<"\n" ;
// output each array element's value
for (size_t i{0}; i < a.size(); ++i) {
std::cout << i << a[i]<<"\n";
}
}
int main() {
std::array<int, 5> values{}; // values is an array of 5 int values
std::array<double,10> floatarray;
std::vector<double> floatvector(20, 0);
for (size_t i{0}; i < floatarray.size(); i++)
floatarray[i] = i*i/10.0;
// initialize elements of array values to 0
for (size_t i{0}; i < values.size(); ++i) {
values[i] = 0; // set element at location i to 0
values[i] = i*i; // set element at location i to 0
}
std::cout << std::format("{:>7}{:>10}\n", "Element", "Value");
// output each array element's value
for (size_t i{0}; i < values.size(); ++i) {
std::cout << std::format("{:>7}{:>10}\n", i, values[i]);
}
std::cout << std::format("\n{:>7}{:>10}\n", "Element", "Value");
printArray(values,"values");
printArray(floatarray,"floatarray");
printArray(floatvector, "floatvector");
std::cout << "Element Value\n" << "\n";
floatvector.resize(5);
printArray(floatvector,"floatvector resized");
// access elements via the at member function
for (size_t i{0}; i < values.size(); ++i) {
std::cout << std::format("{:>7}{:>10}\n", i, values.at(i));
std::cout << i<<values.at(i) <<"\n";
}
for (auto i : values){
std::cout << std::format("{:>7}{:>8}\n", i, values.at(i));
/* for (auto i : values){
std::cout << i << values.at(i)<<"\n";
}
*/
// accessing an element outside the array's bounds with at
values.at(10); // throws an exception
// values.at(10); // throws an exception
}
/**************************************************************************