ch2-Intvector
Chapter_2 Exercise_2-7 | Exercise_2-8 |
Intvector.cpp TCP1, p. 117-118 download
// Creating a vector that holds integers
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int main()
{
vector<int> v;
for(int i = 0; i < 10; i++)
{v.push_back(i);}
int size = v.size();
for(int i = 0; i < size; i++)
{cout << v[i] << ", ";}
cout << endl;
for(int i = 0; i < size; i++)
{v[i] *= 10;} // v[i] = v[i] * 10;
for(int i = 0; i < size; i++)
{cout << v[i] << ", ";}
cout << endl;
}
/*
g++ Intvector.cpp -o Intvector
./Intvector
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 10, 20, 30, 40, 50, 60, 70, 80, 90,
*/
Note:
The function call v.size() is expensive inside a loop, so we store the size of v in an
int variable and then refer to this variable inside the loops:
int size = v.size();
for(int i = 0; i < size; i++)
Chapter_2 Exercise_2-7 | BACK_TO_TOP | Exercise_2-8 |
Comments
Post a Comment