1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
unsigned randNum(unsigned min, unsigned max)
{
return min + rand() % (max-min+1) ;
}
std::vector<std::vector<unsigned>> generateVector(unsigned vecs, unsigned vecElements)
{
std::vector<std::vector<unsigned>> v(vecs, std::vector<unsigned>(vecElements)) ;
for ( auto& vec : v )
for ( auto& num : vec )
num = randNum(100,999) ;
return v ;
}
bool writeVector(std::ostream & os, const std::vector<std::vector<unsigned>>& v)
{
if ( os )
{
for ( auto & e : v )
{
std::copy(e.begin(), e.end(), std::ostream_iterator<unsigned>(os, " ")) ;
os << '\n' ;
}
}
return os ;
}
std::vector<std::vector<unsigned>> readVector(std::istream& is)
{
std::vector<std::vector<unsigned>> v ;
std::string line ;
std::istringstream numStream;
while ( std::getline(is, line) )
{
v.resize(v.size()+1) ;
numStream.clear() ;
numStream.str(line) ;
std::copy(std::istream_iterator<unsigned>(numStream),
std::istream_iterator<unsigned>(),
std::back_inserter(v.back())) ;
}
return v ;
}
int main()
{
std::srand(static_cast<std::size_t>(std::time(0))) ;
const std::string filename("vector.txt") ;
auto v = generateVector(10, 10) ;
{
std::ofstream os(filename) ;
writeVector(std::cout, v) ;
writeVector(os, v) ;
}
std::cout << '\n' ;
std::vector<std::vector<unsigned>> u ;
{
std::ifstream is(filename) ;
u = readVector(is) ;
writeVector(std::cout, u) ;
}
if ( u == v )
std::cout << "Success!\n" ;
else
std::cout << "Failed!\n" ;
}
|