63 lines
2.5 KiB
C++
63 lines
2.5 KiB
C++
// fig06_01.cpp
|
|
// Initializing an array's elements to zeros and printing the array.
|
|
//#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] = i*i; // set element at location i to 0
|
|
}
|
|
|
|
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 << i<<values.at(i) <<"\n";
|
|
}
|
|
/* 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
|
|
}
|
|
|
|
/**************************************************************************
|
|
* (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. *
|
|
**************************************************************************/
|