Skip to content

Instantly share code, notes, and snippets.

@Aethelflaed
Created August 20, 2014 13:50
Show Gist options
  • Save Aethelflaed/6d8c30511f0a2d731fde to your computer and use it in GitHub Desktop.
Save Aethelflaed/6d8c30511f0a2d731fde to your computer and use it in GitHub Desktop.
linear C array to 2D std::vector
#include <iostream>
#include <vector>
template<typename T>
struct myIterator : public std::iterator<std::input_iterator_tag, T*>
{
myIterator(T* data) :
data(data)
{}
T* data;
bool operator==(const myIterator& rhs){return rhs.data == data;}
bool operator!=(const myIterator& rhs){return rhs.data != data;}
T* operator*(){return data;}
T* operator->(){return data;}
myIterator& operator++(){data = &data[1]; return *this; }
};
int main() {
int myData[] = {
1, 2, 3,
4, 5, 6,
7, 8, 9
};
size_t w = 3, h = 3;
std::vector<std::vector<int*>> data;
data.reserve(w);
for (size_t i = 0; i < w; ++i)
{
data.emplace_back(myIterator<int>(&myData[i * h]),
myIterator<int>(&myData[(i + 1) * h]));
}
for (const auto& i : data)
for (const auto& j : i)
std::cout << *j << std::endl;
std::cout << "or with index access: " << std::endl;
for (size_t i = 0; i < w; ++i)
for (size_t j = 0; j < h; ++j)
std::cout << *data[i][j] << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment