How to print out the contents of a vector?

2018-12-31 15:34发布

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?

13条回答
素衣白纱
2楼-- · 2018-12-31 15:42

In C++11, a range-based for loop might be a good solution:

vector<char> items = {'a','b','c'};
for (char n : items)
    cout << n << ' ';

Output:

a b c 
查看更多
残风、尘缘若梦
3楼-- · 2018-12-31 15:42

In C++11``

for (auto i = path.begin(); i != path.end(); ++i)
std::cout << *i << ' ';

for(int i=0; i<path.size(); ++i)
std::cout << path[i] << ' ';
查看更多
刘海飞了
4楼-- · 2018-12-31 15:43

A much easier way to do this is with the standard copy algorithm:

#include <iostream>
#include <algorithm> // for copy
#include <iterator> // for ostream_iterator
#include <vector>

int main() {
    /* Set up vector to hold chars a-z */
    std::vector<char> path;
    for (int ch = 'a'; ch <= 'z'; ++ch)
        path.push_back(ch);

    /* Print path vector to console */
    std::copy(path.begin(), path.end(), std::ostream_iterator<char>(std::cout, " "));

    return 0;
}

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.

查看更多
闭嘴吧你
5楼-- · 2018-12-31 15:43

The problem is probably in the previous loop: (x = 17; isalpha(firstsquare); x++). This loop will run not at all (if firstsquare is non-alpha) or will run forever (if it is alpha). The reason is that firstsquare doesn't change as x is incremented.

查看更多
十年一品温如言
6楼-- · 2018-12-31 15:45

How about for_each + lambda expression:

#include <vector>
#include <algorithm>
...
std::vector<char> vec;
...
std::for_each(
              vec.cbegin(),
              vec.cend(),
              [] (const char c) {std::cout << c << " ";} 
              );
...

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.

查看更多
梦寄多情
7楼-- · 2018-12-31 15:46

overload operator<<:

template<typename OutStream, typename T>
OutStream& operator<< (OutStream& out, const vector<T>& v)
{
    for (auto const& tmp : v)
        out << tmp << " ";
    out << endl;
    return out;
}

Usage:

vector <int> test {1,2,3};
wcout << test; // or any output stream
查看更多
登录 后发表回答