[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
Cpp2dVector
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
Cpp2dVector
(C++) Two-dimensional std::vectors
Like arrays, vectors can also be two-dimensional. 2-D vectors can be used as matrices.Create and resize example
The code shows how to create and use them. 2D vectors can be created in either multiple lines (using the resize method or using its flexible constructor. The latter yields a more complex-looking line.int main() { { //Multi-line construction const int maxx = 10; const int maxy = 5; std::vector<std::vector<int> > vec; vec.resize(maxx); for (int i=0; i<maxx; ++i) { vec[i].resize(maxy); } vec.at(maxx-1).at(maxy-1) = 10; std::cout << vec[maxx-1][maxy-1] << std::endl; assert(vec.size() == maxx); assert(vec[0].size() ==maxy); } { //One-line construction const int maxx = 10; const int maxy = 5; std::vector<std::vector<int> > vec(maxx,std::vector<int>(maxy,0)); vec.at(maxx-1).at(maxy-1) = 10; std::cout << vec[maxx-1][maxy-1] << std::endl; assert(vec.size() == maxx); assert(vec[0].size() == maxy); } { //One-line construction const int maxx = 5; const int maxy = 10; std::vector<std::vector<int> > vec(maxx,std::vector<int>(maxy,0)); vec.at(maxx-1).at(maxy-1) = 10; std::cout << vec[maxx-1][maxy-1] << std::endl; assert(vec.size() ==maxx); assert(vec[0].size() ==maxy); } std::cout << "Done" << std::endl; }
- include <iostream>
- include <cassert>
- include <vector>
std::cout on a 2D std::vector
Can be done overloading the stream out operator.//Works for std::vector that are saved [x][y] template <class T> std::ostream& operator<<(std::ostream& os, const std::vector<std::vector<T> >& v) { const int maxx = v.size(); if (maxx == 0) { os << "{empty std::vector}"; } else { const int maxy = v[0].size(); for (int y=0; y!=maxy; ++y) { for (int x=0; x!=maxx; ++x) { os << static_cast<int>(v[x][y]); } os << '\n'; } } return os; } //Works for std::vector that are saved [y][x] template <class T> std::ostream& operator<<(std::ostream& os, const std::vector<std::vector<T> >& v) { if (v.size() == 0) { os << "{empty std::vector}"; } else { for ( std::vector<std::vector<T> >::const_iterator y=v.begin(); y!=v.end(); ++y) { for ( std::vector<T>::const_iterator x=(*y).begin(); x!=(*y).end(); ++x) { os << static_cast<int>(*x); } os << '\n'; } } return os; } int main() { const std::vector<std::vector<unsigned char> > image(20,std::vector<unsigned char>(10,127)); std::cout << std::hex << image << std::dec << '\n'; }
- include <vector>
- include <iostream>
Code links
- #include
- assert
- cassert (header file)
- cin
- const
- cout
- include
- int
- iostream (header file)
- main
- return
- vector
- vector (header file)
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
