I want to print out the contents of a vector in C++, here is what I have:
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <sstream>
#include <cstdio>
using namespace std;
int main()
{
ifstream file("maze.txt");
if (file) {
vector<char> vec(istreambuf_iterator<char>(file), (istreambuf_iterator<char>()));
vector<char> path;
int x = 17;
char entrance = vec.at(16);
char firstsquare = vec.at(x);
if (entrance == 'S') {
path.push_back(entrance);
}
for (x = 17; isalpha(firstsquare); x++) {
path.push_back(firstsquare);
}
for (int i = 0; i < path.size(); i++) {
cout << path[i] << " ";
}
cout << endl;
return 0;
}
}
How do I print the contents of the vector to the screen?
In C++11, a range-based for loop might be a good solution:
Output:
In C++11``
A much easier way to do this is with the standard copy algorithm:
The ostream_iterator is what's called an iterator adaptor. It is templatized over the type to print out to the stream (in this case,
char
).cout
(aka console output) is the stream we want to write to, and the space character (" "
) is what we want printed between each element stored in the vector.This standard algorithm is powerful and so are many others. The power and flexibility the standard library gives you are what make it so great. Just imagine: you can print a vector to the console with just one line of code. You don't have to deal with special cases with the separator character. You don't need to worry about for-loops. The standard library does it all for you.
The problem is probably in the previous loop:
(x = 17; isalpha(firstsquare); x++)
. This loop will run not at all (iffirstsquare
is non-alpha) or will run forever (if it is alpha). The reason is thatfirstsquare
doesn't change asx
is incremented.How about
for_each
+ lambda expression:Of course, a range-based for is the most elegant solution for this concrete task, but this one gives many other possibilities as well.
Explanation
The
for_each
algorithm takes an input range and a callable object, calling this object on every element of the range. An input range is defined by two iterators. A callable object can be a function, a pointer to function, an object of a class which overloads() operator
or as in this case, a lambda expression. The parameter for this expression matches the type of the elements from vector.The beauty of this implementation is the power you get from lambda expressions - you can use this approach for a lot more things than just printing the vector.
overload operator<<:
Usage: