[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppCopy
Prefer algorithm calls over hand-written loops [1,2].
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppCopy
(C++) std::copy
STL algorithm to copy containers.Prefer algorithm calls over hand-written loops [1,2].
Example
Copies a std::map to a std::vector.int main() { const int size = 10; //Generate a std::map std::map<int,int> myMap; for (int i=0; i!=size; ++i) myMap[i] = i*i; //Generate a std::vector std::vector<std::pair<int,int> > myVector; myVector.resize(size); //Copy the std::map to the std::vector std::copy(myMap.begin(),myMap.end(),myVector.begin()); assert(myVector.size()==10); //Display the std::vector for (int i=0; i!=10; ++i) { std::cout << myVector[i].first << " " << myVector[i].second << std::endl; } }
- include <map>
- include <vector>
- include <algorithm>
- include <cassert>
- include <iostream>
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]
