[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppFor
This enables you to count from value X to (and not including) value Y in steps of Z:
Most for loops are used for working with arrays, std::vectors or other indexable classes or data types. As indexes start at 0 and cannot be negative, an indexing for loop, looks like this:
Prefer algorithm calls over hand-written loops [1,2].
When using STL classes like std::vector, there are techniques, using iterators and std::for_each:
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppFor
(C++) for
Keyword enabling you to perform a for-loop.
for( [initialization] ; [condition] ; [step] )
{
[statements]
}
This enables you to count from value X to (and not including) value Y in steps of Z:
int main() { const double X = 69.69; const double Y = 96.96; const double Z = 0.69; for (double counter=X; counter<Y; counter+=Z) { std::cout << counter << std::endl; } }
- include <iostream>
Most for loops are used for working with arrays, std::vectors or other indexable classes or data types. As indexes start at 0 and cannot be negative, an indexing for loop, looks like this:
int main() { //Create a random-sized std::vector std::vector<int> myVector(rand()%100); //Fill it with random values const int myVectorSize = myVector.size(); for (int i=0; i!=myVectorSize; ++i) { myVector[i] = rand()%69; } //Print it to screen for (int i=0; i!=myVectorSize; ++i) { std::cout << i << " : " << myVector[i] << std::endl; } }
- include <iostream>
- include <vector>
Prefer algorithm calls over hand-written loops [1,2].
When using STL classes like std::vector, there are techniques, using iterators and std::for_each:
int main() { //Create a random-sized std::vector std::vector<double> myVector(100); //Fill it with random values const int myVectorSize = myVector.size(); for (int i=0; i!=myVectorSize; ++i) { myVector[i] = sqrt(rand()%69); } //Print it to screen for (std::vector<double>::const_iterator i = myVector.begin(); i!=myVector.end(); ++i) { std::cout << *i << std::endl; } }
- include <iostream>
- include <vector>
Topic links
- ::, scope operator
- <<, stream out operator
- ++, increment operator
- const
- cout
- double
- endl
- for_each
- #include
- iostream
- main
- rand
- return
- std
- std::for_each
- std::rand
- std::vector
- vector
'for' links
References
- 1) Bjarne Stroustrup. The C++ Programming Language (3rd edition).ISBN: 0-201-88954-4. Chapter 18.12.1: 'Prefer algorithms to loops]].
- 2) Scott Meyers. Effective STL. ISBN: 0-201-74962-9. Item 43: 'Prefer algorithm calls over hand-written loops'
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
