2

我有两个要以 CSV 格式写入文件的向量。我可以使用 for 循环“手动”执行此操作,但我第一次尝试使用 boost zip_iterator。这就是我能走多远。(网络版

请注意,这适用于遗留项目,因此我不能使用较新版本的 C++(例如 C++11、C++14、C++17)

#include <vector>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <boost/tuple/tuple.hpp>
#include <boost/iterator/zip_iterator.hpp>

typedef boost::tuples::tuple<unsigned,unsigned> DataPair;
typedef std::ostream_iterator<DataPair> DataPairOStream;

// Error messages suggest that something resembling this overload might be needed.
// This however does not solve the problem.
DataPairOStream& operator<<( DataPairOStream& stream , const DataPair& )
{
    return stream;
}

int main()
{
    std::vector<unsigned> data1( 10 , 1 );
    std::vector<unsigned> data2( 10 , 2 );

    std::ofstream outputFile( "Foo.txt" );
    DataPairOStream outputIterator( outputFile , "\n" );   // ???

    std::copy(
        boost::make_zip_iterator( boost::make_tuple( data1.begin() , data2.begin() ) ) ,
        boost::make_zip_iterator( boost::make_tuple( data1.end()   , data2.end()   ) ) ,
        outputIterator ); 
}

错误消息的片段(整个内容太长,无法粘贴)

/usr/lib/gcc/i686-pc-cygwin/6.4.0/include/c++/bits/stream_iterator.h:198:13: error: no match for ‘operator<<’ (operand types are ‘std::ostream_iterator<boost::tuples::tuple<unsigned int, unsigned int> >::ostream_type {aka std::basic_ostream<char>}’ and ‘const boost::tuples::tuple<unsigned int, unsigned int>’)
  *_M_stream << __value;
  ~~~~~~~~~~~^~~~~~~~~~
4

2 回答 2

2

这个应该很好用。现在 ADL 找到了operator<<重载,因为它被放在了命名空间中boost::tuples

#include <vector>
#include <fstream>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <boost/tuple/tuple.hpp>
#include <boost/iterator/zip_iterator.hpp>

typedef boost::tuples::tuple<unsigned,unsigned> DataPair;

namespace boost{
namespace tuples{

std::ostream & operator<<( std::ostream& stream , const DataPair& )
{
    return stream;
}

}
}

int main()
{
    std::vector<unsigned> data1( 10 , 1 );
    std::vector<unsigned> data2( 10 , 2 );

    std::ofstream outputFile( "Foo.txt" );
    std::ostream_iterator<DataPair> outputIterator( outputFile , "\n" ); 

    std::copy(
        boost::make_zip_iterator( boost::make_tuple( data1.begin() , data2.begin() ) ) ,
        boost::make_zip_iterator( boost::make_tuple( data1.end()   , data2.end()   ) ) ,
        outputIterator ); 
}

在实践中投入operator <<std有效,但不应该这样做,因为它是未定义的行为

于 2018-02-15T14:21:32.253 回答
1

DataPairOStream迭代器而不是。它适应std::ostream迭代器接口。

你需要定义

std::ostream & operator<< (std::ostream & os, const DataPair & dp)
{
    return os << boost::tuples::get<0>(dp) << boost::tuples::get<1>(dp);
}
于 2018-02-15T14:07:51.080 回答