如何打印出一个向量的内容? [英] How to print out the contents of a vector?

查看:102
本文介绍了如何打印出一个向量的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C ++打印一个向量的内容,这里是我有:

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?

推荐答案

纯粹回答你的问题,可以使用迭代器:

Purely to answer your question you, can use an iterator:

std::vector<char> path;
// ...
for (std::vector<char>::const_iterator i = path.begin(); i != path.end(); ++i)
    std::cout << *i << ' ';

如果要在for循环中修改向量的内容,请使用迭代器而不是 const_iterator

If you want to modify the vector's contents in the for loop, then use iterator rather than const_iterator.

但还有很多可以说。如果你只想要一个答案,你可以使用,那么你可以在这里停止;

But there's lots more that can be said about this. If you just want an answer you can use, then you can stop here; otherwise, read on.

这不是另一个解决方案,而是对上述迭代器解决方案的补充。如果您使用的是C ++ 11标准(或更高版本),那么您可以使用 auto 关键字来提高可读性:

This is not another solution, but a supplement to the above iterator solution. If you are using the C++11 standard (or later), then you can use the auto keyword to help the readability:

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

但是 i -const(即,编译器将使用 i 的类型 std :: vector< char> :: iterator )。

But the type of i will be non-const (i.e., the compiler will use std::vector<char>::iterator as the type of i).

在这种情况下,你可以使用 typedef (不限于C ++ 11 ,非常有用):

In this case, you might as well just use a typedef (not restricted to C++11, and very useful to use anyway):

typedef std::vector<char> Path;
Path path;
// ...
for (Path::const_iterator i = path.begin(); i != path.end(); ++i)
    std::cout << *i << ' ';



计数器



,请使用整数类型在中为循环记录您的位置:

counter

You can, of course, use a integer type to record your position in the for loop:

for(int i=0; i<path.size(); ++i)
  std::cout << path[i] << ' ';

如果你打算这样做,最好使用容器的成员类型并适当。 std :: vector 对于此作业有一个名为 size_type 的成员类型: size 方法。

If you are going to do this, it's better to use the container's member types, if they are available and appropriate. std::vector has a member type called size_type for this job: it is the type returned by the size method.

// Path typedef'd to std::vector<char>
for( Path::size_type i=0; i<path.size(); ++i)
  std::cout << path[i] << ' ';

为什么不能在迭代器解?对于简单的情况下,你也可以,但重点是, iterator 类是一个对象,旨在为更复杂的对象做这个工作,这个解决方案不会是理想的。

Why not just use this over the iterator solution? For simple cases you might as well, but the point is that the iterator class is an object designed to do this job for more complicated objects where this solution is not going to be ideal.

请参阅 Jefffrey的解决方案。在C ++ 11(和更高版本)中,您可以使用新的基于范围的 for 循环,如下所示:

See Jefffrey's solution. In C++11 (and later) you can use the new range-based for loop, which looks like this:

for (auto i: path)
  std::cout << i << ' ';

由于 path 显式地 std :: vector< char> ),对象 i 是向量项的类型,显式地,它是类型 char )。对象 i 有一个值,它是 path 对象中实际项目的副本。因此,循环中 i 的所有更改不会保留在 path 本身中。此外,如果您想强制您不想在循环中更改复制的 i 值,您可以强制类型 i 为 const char 如下:

Since path is a vector of items (explicitly std::vector<char>), the object i is of type of the item of the vector (i.e., explicitly, it is of type char). The object i has a value that is a copy of the actual item in the path object. Thus, all changes to i in the loop are not preserved in path itself. Additionally, if you would like to enforce the fact that you don't want to be able to change the copied value of i in the loop, you can force the type of i to be const char like this:

for (const auto i: path)
  std::cout << i << ' ';

如果您要修改 path ,可以使用引用:

If you would like to modify the items in path, you can use a reference:

for (auto& i: path)
  std::cout << i << ' ';

,即使您不想修改 path ,如果对象的复制是昂贵的,你应该使用const引用,而不是通过值复制:

and even if you don't want to modify path, if the copying of objects is expensive you should use a const reference instead of copying by value:

for (const auto& i: path)
  std::cout << i << ' ';



std :: copy



a href =http://stackoverflow.com/a/11335634/498730> Joshua的回答。您可以使用STL算法 std :: copy 将向量内容复制到输出流。这是一个优雅的解决方案,如果你很舒服(除此之外,它非常有用,不只是在这种情况下打印矢量的内容)。

std::copy

See Joshua's answer. You can use the STL algorithm std::copy to copy the vector contents onto the output stream. This is an elegant solution if you are comfortable with it (and besides, it is very useful, not just in this case of printing the contents of a vector).

请参阅 Max的解决方案< a>。对于这个简单的场景,使用 std :: for_each 是过度的,但如果你想做的不仅仅是打印到屏幕,这是一个非常有用的解决方案:using std :: for_each 允许您对向量内容执行任何(明智的)操作。

See Max's solution. Using std::for_each is overkill for this simple scenario, but it is a very useful solution if you wanted to do more than just printing to screen: using std::for_each allows you to do any (sensible) operation on the vector contents.

请参阅 Chris的回答,是更多的补充其他答案,因为你仍然需要实现上面的解决方案之一在重载。在他的例子中,他在中使用了一个计数器,用于循环。例如,您可以快速使用 Joshua的解决方案

See Chris's answer, this is more a complement to the other answers since you will still need to implement one of the solutions above in the overloading. In his example he used a counter in a for loop. For example, this is how you could quickly use Joshua's solution:

template <typename T>
std::ostream& operator<< (std::ostream& out, const std::vector<T>& v) {
  if ( !v.empty() ) {
    out << '[';
    std::copy (v.begin(), v.end(), std::ostream_iterator<T>(out, ", "));
    out << "\b\b]";
  }
  return out;
}

任何其他解决方案的使用应该很简单。

Usage of any of the other solutions should be straightforward.

此处提供的任何解决方案都可以使用。它取决于你和代码上哪一个是最好的。任何比这更详细的可能最好留给另一个问题的优点/缺点可以正确评估;但是一如既往的用户偏好总是会发挥作用:没有一个解决方案是错误的,但有些将看起来更好的每个个人编码器。

Any of the solutions presented here will work. It's up to you and the code on which one is the "best". Anything more detailed than this is probably best left for another question where the pros/cons can be properly evaluated; but as always user preference will always play a part: none of the solutions presented are wrong, but some will look nicer to each individual coder.

这是我发布的较早版本的扩展解决方案。从那个职位不断引起注意,我决定扩大它,并参考其他优秀的解决方案,发布在这里。我的原始帖子有一句话,提到如果你打算修改你的向量在 循环,那么有两个方法提供 std :: vector 来访问元素: std :: vector :: operator [] code> std :: vector :: at ,它会执行边界检查。换句话说,会抛出,如果你尝试访问一个元素的向量和 operator [] 不会。我只添加了这个评论,最初,为了提到的东西,它可能是有用的,知道是否有人已经没有。我现在没有什么区别。因此本增编。

This is an expanded solution of an earlier one I posted. Since that post kept getting attention, I decided to expand on it and refer to the other excellent solutions that were posted here. My original post had a remark that mentioned that if you were intending on modifying your vector inside a for loop then there are two methods provided by std::vector to access elements: std::vector::operator[] which does not do bounds checking, and std::vector::at which does perform bounds checking. In other words, at will throw if you try to access an element outside the vector and operator[] wouldn't. I only added this comment, originally, for the sake of mentioning something that it might be useful to know of if anyone already didn't. And I see no difference now. Hence this addendum.

这篇关于如何打印出一个向量的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆