简体   繁体   English

重载ostream&<<以从类中以相反顺序输出向量

[英]Overloading ostream&<< to output a vector in reverse order from a class

I have defined a class with a public vector and I am trying to output each member of the vector in the reverse order using reverse iterators. 我已经定义了一个带有公共向量的类,并且我试图使用反向迭代器以相反的顺序输出向量的每个成员。

std::ostream& operator<<(std::ostream& os, const bignum& num)
{
   for (std::vector<char>::reverse_iterator p = num.vec.rbegin(); p != num.vec.rend(); ++p)
      os << static_cast<int>(*p);
   return os;
}

This thing doesn't compile and I am a bit confused on what is wrong. 这东西不能编译,我对什么地方有点困惑。 Thanks. 谢谢。

You have to use const_reverse_iterator: 您必须使用const_reverse_iterator:

std::ostream & operator<<( std::ostream &os, const bignum &num ) 
{
    for ( std::vector<char>::const_reverse_iterator p = num.vec.rbegin();  
          p != num.vec.rend();  ++p )
        os << static_cast<int>(*p);

    return os;
}

Also you could use standard algorithm, std::copy . 您也可以使用标准算法std::copy For example 例如

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

//...

std::ostream & operator<<( std::ostream &os, const bignum &num ) 
{
    std::copy( num.vec.rbegin(), num.vec.rend(),
               std::ostream_iterator<int>( os ) );

    return os;
}

Since you're receiving a reference to a const bignum , you'd need a const_reverse_iterator , not just a reverse_iterator . 由于您正在收到对const bignum的引用,因此需要const_reverse_iterator ,而不仅是reverse_iterator

I'd just use std::copy instead though: 我只是使用std::copy代替:

std::copy(num.vec.rbegin(), num.vec.rend(), std::ostream_iterator<int>(os));

All the answers shown provide great ways of doing it, I'll just throw in my 2 cents: 所显示的所有答案都提供了很好的方法,我只花2美分:

std::for_each(num.vec.rbegin(),num.vec.rend(),[](int x){
  std::cout << x << std::endl; // or any delimeter you wish
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM