[C++-sig] vector<> to string

Andreas Beyer mail at a-beyer.de
Mon May 8 15:15:30 CEST 2006


François Duranleau wrote:

> On Fri, 5 May 2006, Andreas Beyer wrote:
>
>> // convert vector into python-style string
>> std::ostream& operator<<(std::ostream& os, const 
>> std::vector<VALUE_T>& v) {
>
> [...]
>
>> }
>
>
[...]

>
> The simple solution is to declare the operator<< in namespace std. 
> Actually, it is usually better, I think, to declare operators in the 
> same namespace as the manipulated types.

Excellent, this solves the issue.

>
> P.S.: In the definition of your operator, you use:
>      operator<<(os, lexical_cast<std::string>(*it));
> Why bother with the lexical_cast here? Why not simply write:
>      os << *it;
> ? It would also be more efficient.

For what ever reason it only works if I use boost::lexical_cast<>. 
Otherwise I get the same compile error:

gcc-C++-action 
bin/csrc/str_test.so/gcc/release/shared-linkable-true/vector_writer.o
vector_writer.cpp: In function `std::ostream& std::operator<<(std::ostream&,
   const std::vector<int, std::allocator<int> >&)':
vector_writer.cpp:60: error: call of overloaded `operator<<(
   std::basic_ostream<char, std::char_traits<char> >&, const int&)' is
   ambiguous


Andreas


PS: Here is the "final" template, which works for MyInt and for int. 
Maybe something like this could be added to the indexing suite.

namespace std{
   // convert vector into python-style string
   template<class T>
   std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
    typedef std::vector<T> vtype;
    os << "[";
    typename vtype::const_iterator end = v.end();
    for(typename vtype::const_iterator it = v.begin(); it!=end; it++) {
        operator<< (os, boost::lexical_cast<std::string>(*it) );
        if (it<end-1) os << ", ";
    }
    os << "]";
    return os;
   }
}





More information about the Cplusplus-sig mailing list