c-resources/CPlusPlus20ForProgrammers-m.../examples/ch06/fig06_01.cpp

63 lines
2.5 KiB
C++
Raw Normal View History

2024-04-09 06:45:18 +00:00
// fig06_01.cpp
// Initializing an array's elements to zeros and printing the array.
2024-04-09 08:36:48 +00:00
//#include <../libraries/fmt/include/format.h> // C++20: This will be #include <format>
2024-04-09 06:45:18 +00:00
#include <iostream>
#include <array>
2024-04-09 08:36:48 +00:00
#include <vector>
#include <string>
2024-04-09 06:45:18 +00:00
2024-04-09 08:36:48 +00:00
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";
}
}
2024-04-09 06:45:18 +00:00
int main() {
std::array<int, 5> values{}; // values is an array of 5 int values
2024-04-09 08:36:48 +00:00
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;
2024-04-09 06:45:18 +00:00
// initialize elements of array values to 0
for (size_t i{0}; i < values.size(); ++i) {
2024-04-09 08:36:48 +00:00
values[i] = i*i; // set element at location i to 0
2024-04-09 06:45:18 +00:00
}
2024-04-09 08:36:48 +00:00
printArray(values,"values");
printArray(floatarray,"floatarray");
printArray(floatvector, "floatvector");
std::cout << "Element Value\n" << "\n";
floatvector.resize(5);
printArray(floatvector,"floatvector resized");
2024-04-09 06:45:18 +00:00
// access elements via the at member function
for (size_t i{0}; i < values.size(); ++i) {
2024-04-09 08:36:48 +00:00
std::cout << i<<values.at(i) <<"\n";
2024-04-09 06:45:18 +00:00
}
2024-04-09 08:36:48 +00:00
/* for (auto i : values){
std::cout << i << values.at(i)<<"\n";
2024-04-09 06:45:18 +00:00
}
2024-04-09 08:36:48 +00:00
*/
2024-04-09 06:45:18 +00:00
// accessing an element outside the array's bounds with at
2024-04-09 08:36:48 +00:00
// values.at(10); // throws an exception
2024-04-09 06:45:18 +00:00
}
/**************************************************************************
* (C) Copyright 1992-2022 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/