473,715 Members | 3,751 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

copy map to ostream_iterato r

std::copy to std::ostream_it erator doesn't seem to
work with maps and pairs.

Shouldn't I expect something like this to work?

The G++ error message when USE_COPY_TO_PRI NT is
defined as a non-zero number follows.

---------------- error message --------------------

<snip lower 'instantiated from' template chain>

constCorrectnes s.cpp:99: instantiated from here
/usr/include/c++/3.3.1/bits/stream_iterator .h:141: e
rror: no match for
'operator<<' in '*this->std::ostream_i terator<Pair
II, char,
std::char_trait s<char> >::_M_stream << __value'
<snip candidate templates list>

-------------------- environment -------------------

Windows 2K, CygWin, g++

--------------------- makefile ---------------------

#!/usr/bin make

printmaps.exe : \
printmaps.o
printmaps.o : \
printmaps.cpp

%.exe : %.o
g++ -g -pedantic -Os -fexceptions -o $@ $^
%.o : %.cpp
g++ -g -pedantic -Os -fexceptions -o $@ -c $<
# EOF

------------------- compiler -----------------------
cmd /c g++ --version

g++ (GCC) 3.3.1 (cygming special)
Copyright (C) 2003 Free Software Foundation, Inc.
This is free software; see the source for copying co
nditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FO
R A PARTICULAR PURPOSE.

------------------- source code --------------------
#include <map>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <sstream>

// -------------------------------------------------
// PROBLEM NOTE:
// Everything compiles with USE_COPY_TO_PRI NT
// set to 0. Set to 1 to show the problem.
// -------------------------------------------------

#define USE_COPY_TO_PRI NT 1

typedef std::pair<int ,int> PairII;

std::string
to_s(PairII const & pii) {
std::stringstre am ss;
ss << "(" << pii.first << ","
<< pii.second << ")";
return ss.str();
}

std::ostream &
operator << (
std::ostream & os,
PairII const & pii) {
os << to_s(pii);
return os;
}

#if !USE_COPY_TO_PR INT

// -------------------------------------------------
// PROBLEM NOTE:
// This is a helper for the work-around.
// -------------------------------------------------

void
print(PairII const & pii) {
std::cout << to_s(pii) << "\n";
}

#endif

int main() {
size_t const N(5);
PairII a[N] = {
PairII(1,2),
PairII(3,4),
PairII(5,6),
PairII(7,8),
PairII(9,10)
};
std::map<int,in t> m(
a,
a + N
);
std::cout << a[0] << "\n";
std::cout << *m.begin() << "\n";

#if USE_COPY_TO_PRI NT

// -------------------------------------------------
// PROBLEM NOTE:
// This is the part that doesn't work.
// -------------------------------------------------

std::copy(
a,
a + N,
std::ostream_it erator<PairII>(
std::cout,
"\n"
)
);
std::copy(
m.begin(),
m.end(),
std::ostream_it erator<PairII>(
std::cout,
"\n"
)
);

#else

// -------------------------------------------------
// PROBLEM NOTE:
// This is the work around.
// -------------------------------------------------

std::for_each(
a,
a + N,
print
);
std::for_each(
m.begin(),
m.end(),
print
);

#endif

}
// EOF
--
Jeff

Vote Constitution Party! --Jeff
Jul 22 '05 #1
8 4615

"Jeff" <je************ ******@hotmail. com> wrote in message
news:1n******** *************** ******@40tude.n et...
std::copy to std::ostream_it erator doesn't seem to
work with maps and pairs.

Shouldn't I expect something like this to work?


Well perhaps. But there is no insertion operator defined for pairs by the
C++ standard, and surprisingly there is no useful way to define one.

This does not work

template <class T, class U>
ostream& operator<<(ostr eam& out, std::pair<T, U> const& p)
{
...
}

because the compiler will not look in the global namespace when trying to
find an operator<< for std::ostream and std::pair. The only namespace it
will look at is the std namespace, so this might work

namespace std
{
template <class T, class U>
ostream& operator<<(ostr eam& out, std::pair<T, U> const& p)
{
...
}
}

but it is not legal C++ because it is not legal to add definitions to the
std namespace.

In my view this is a defect in the C++ language.

john
Jul 22 '05 #2

"John Harrison" <jo************ *@hotmail.com> wrote in message
news:2s******** *****@uni-berlin.de...

"Jeff" <je************ ******@hotmail. com> wrote in message
news:1n******** *************** ******@40tude.n et...
std::copy to std::ostream_it erator doesn't seem to
work with maps and pairs.

Shouldn't I expect something like this to work?


Well perhaps. But there is no insertion operator defined for pairs by the
C++ standard, and surprisingly there is no useful way to define one.

This does not work

template <class T, class U>
ostream& operator<<(ostr eam& out, std::pair<T, U> const& p)
{
...
}

because the compiler will not look in the global namespace when trying to
find an operator<< for std::ostream and std::pair.


I should add that this is only because the compiler is looking for
operator<< from within std::copy which obviously is in the std namespace. If
you wrote your own version of std::copy in the global namespace, then I
believe it would work.

john
Jul 22 '05 #3
>
I should add that this is only because the compiler is looking for
operator<< from within std::copy


That of course is complete nonsense. operator << is being accessed from
inside std::ostream_it erator, which again is in the std namespace, but a bit
harder to rewrite than std::copy.

john
Jul 22 '05 #4
Jeff <je************ ******@hotmail. com> wrote in message news:<1n******* *************** *******@40tude. net>...
std::copy to std::ostream_it erator doesn't seem to
work with maps and pairs.

Shouldn't I expect something like this to work?


<snipalot/>

No, actually not. std::copy is in std, std::ostream is in std and
std::pair is in std, thus there's no reason why it should look outside
std for a <<. I don't quite understand why it won't let you define the
operator in std though.

For what it's worth, a better workaround than the one you have would
use transform:

std::transform( themap.begin(), themap.end(),
std::ostream_it erator<std::str ing>(cout, "\n"), to_s);
Jul 22 '05 #5
On Sat, 2 Oct 2004 10:28:40 +0100, John Harrison wrote:
namespace std
{
template <class T, class U>
ostream& operator<<(ostr eam& out, std::pair<T, U> const& p)
{
...
}
}


Thanks for your help. That works, but I decided to go with transform so I
don't have to inject into 'std' or rewrite the ostream_iterato r outside of
std.
--
Jeff

Vote Constitution Party! --Jeff
Jul 22 '05 #6
On 2 Oct 2004 07:44:58 -0700, CornedBee wrote:
std::transform( themap.begin(), themap.end(),
std::ostream_it erator<std::str ing>(cout, "\n"), to_s);


Thanks. This works well.

The standard library has failed the least-surprises design criteria on this
point, hasn't it? Shouldn't the designers of pair have included stream
support for it? Maybe not, if they'd have to guess how you want to
represent formatted pairs. There may be lots of options like

(1,2)
1=2
1:2

and so on.
--
Jeff

Vote Constitution Party! --Jeff
Jul 22 '05 #7
"John Harrison" <jo************ *@hotmail.com> wrote in message news:<2s******* ******@uni-berlin.de>...

[ ... ]
this might work

namespace std
{
template <class T, class U>
ostream& operator<<(ostr eam& out, std::pair<T, U> const& p)
{
...
}
}

but it is not legal C++ because it is not legal to add definitions to the
std namespace.


If you look carefully, you'll find that there are circumstances under
which it IS legal to add definitions to the std namespace -- and
unless memory serves me particularly ill tonight, this would fit
within the rules.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 22 '05 #8

"Jerry Coffin" <jc*****@taeus. com> wrote in message
news:b2******** *************** **@posting.goog le.com...
"John Harrison" <jo************ *@hotmail.com> wrote in message
news:<2s******* ******@uni-berlin.de>...

[ ... ]
this might work

namespace std
{
template <class T, class U>
ostream& operator<<(ostr eam& out, std::pair<T, U> const& p)
{
...
}
}

but it is not legal C++ because it is not legal to add definitions to the
std namespace.


If you look carefully, you'll find that there are circumstances under
which it IS legal to add definitions to the std namespace -- and
unless memory serves me particularly ill tonight, this would fit
within the rules.


I think your memory serves you ill. This is covered in 17.4.3.1. The only
exception is for specializations of existing templates. Additional function
overloads (templates or not) are not allowed.

john
Jul 22 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
42783
by: Thomas J. Clancy | last post by:
I was wondering if anyone knew of a way to use std::copy() and istream_iterator<>/ostream_iterator<> write a file copy function that is quick and efficient. Doing this messes up the file because it seems to ignore '\n' ifstream in("somefile"); ofstream out("someOtherFile"); std::copy(std::istream_iterator<unsigned char>(in),
2
1768
by: Severin Ecker | last post by:
hi! i'm trying to copy a file with the std::copy function but my problem is, that whitespaces are discarded. could anyone tell me how i can just copy all the characters that are in the source-file. thx. std::istream_iterator<std::string> ins(in), eos; std::ostream_iterator<std::string> outs(out); std::copy(ins, eos, outs);
6
3217
by: ma740988 | last post by:
There's no way to use the STL algorithm copy to print an outfile (essentially an ofstream)? So now: int main() { std::ifstream InFile( "exercise15.txt"); std::ofstream ToFile( "NewFile.txt" ); //////////////////////////// // Alternative 1
1
2122
by: utab | last post by:
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <iterator> using std::cout; using std::vector; using std::string; using std::endl;
1
3105
by: Siegfried Heintze | last post by:
What is the minimum I must type to create a custom iterator that will allow me display my iterator on std::cout using std::copy? Thanks, Siegfried
9
2449
by: Paulo Matos | last post by:
Hi all, Given a list of int, it's rather easy to output them line by line: std::copy(mylist.begin(), mylist.end(), std::ostream_iterator<int>(cout, "\n"); Now, there's two ways in which I would like to generalize this: First, I would like to be able to print a list of pointers to int. However, I'm guessing this is not possible with copy, right? I would have to:
5
2390
by: Fred | last post by:
Hi: I've got the following request: (suppose the required head file is included) vector<stringvec; // .......... // push some items into vec string str; // here I want to copy some range of elements from vec to str, for example, from vec
2
8114
by: Scofield | last post by:
copy (coll.begin(), coll.end(), ostream_iterator<int>(cout, " ")); when compile, it yields the following errors: list1.cpp:12: error: ¡®ostream_iterator¡¯ was not declared in this scope list1.cpp:12: error: expected primary-expression before ¡®int¡¯ I have included header file iostream and using namespace std; will you please explain why? any solutions?
20
3259
by: Adalte | last post by:
Hi ! When I compile this piece of code I get the following error: "NewShapes.cpp: In function `int main()': NewShapes.cpp:12: error: `ShapePtr' cannot appear in a constant-expression NewShapes.cpp:12: error: template argument 1 is invalid NewShapes.cpp:12: error: template argument 2 is invalid" I may change all code but not change the code in main (sorry), I may add code to the main but not change it. NewShapes.cpp:
0
8718
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9103
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9047
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7973
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6646
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4477
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4738
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3175
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2118
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.