473,804 Members | 3,178 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Print elements of vector

I am wondering what is the "best" code to print out the elements of a
vector.
Assume they contain strings.

With "best", I mean shortest and most readable at the same time.

Of course, a for loop can be done. But I guess one can do it more
elegantly.
Something like this would be possible:

copy(v.begin(), v.end(), ostream_iterato r<string>(cout , "\n"));

But I don't like it: The line begins with "copy", and that's
confusing. It has a kind of misleading semantics.

Then better with for_each. How would that look like? Or is there a
better version?

I wonder why there is no to_string(const string& delimiter) function
in vector. Then, we could write:

cout << v.to_string("\n ") << endl;

Markus
Jul 22 '05 #1
8 25434

"Markus Dehmann" <ma*******@gmx. de> wrote in message
news:c1******** *************** ***@posting.goo gle.com...
I am wondering what is the "best" code to print out the elements of a
vector.
Assume they contain strings.

With "best", I mean shortest and most readable at the same time.

Of course, a for loop can be done. But I guess one can do it more
elegantly.
Something like this would be possible:

copy(v.begin(), v.end(), ostream_iterato r<string>(cout , "\n"));

But I don't like it: The line begins with "copy", and that's
confusing. It has a kind of misleading semantics.

Then better with for_each. How would that look like? Or is there a
better version?

I wonder why there is no to_string(const string& delimiter) function
in vector. Then, we could write:

cout << v.to_string("\n ") << endl;

Markus


IMHO, use arrays directly. With direct access like that, you don't have to
worry about something like this. It would undoubtably be faster -- think
about it. On the inside, a vector is just an easy interface for a linked
list.

-- Matt
Jul 22 '05 #2
On Thu, 15 Jul 2004 12:36:41 -0400, Matthew Del Buono <Pl*******@ToMe .com>
wrote:

IMHO, use arrays directly. With direct access like that, you don't have
to
worry about something like this. It would undoubtably be faster -- think
about it. On the inside, a vector is just an easy interface for a linked
list.


A vector is an easy interface to an array. It has no similarly to a linked
list. And don't knock easy interfaces.

And both of the OP suggestions std::copy and std::for_each are applicable
to arrays as well, so maybe you do have something to worry about.

john
Jul 22 '05 #3
On Thu, 15 Jul 2004 09:19:55 -0700, Markus Dehmann wrote:
Something like this would be possible:

copy(v.begin(), v.end(), ostream_iterato r<string>(cout , "\n"));

But I don't like it: The line begins with "copy", and that's confusing.
It has a kind of misleading semantics.


Here is a to_string that puts the delimiter between the objects, not
after the last one:

#include <sstream>
#include <string>

using namespace std;

template <class Collection>
string to_string(Colle ction const & collection,
char const * delimiter)
{
typedef typename Collection::con st_iterator Iter;

Iter beg = collection.begi n();
Iter const end = collection.end( );

if (beg == end)
{
return string();
}

std::ostringstr eam os;

os << *beg;
++beg;

for ( ; beg != end; ++beg)
{
os << delimiter << *beg;
}

return os.str();
}

template<class Collection>
string to_string(Colle ction const & collection,
string const & delimiter)
{
return to_string(colle ction, delimiter.c_str ());
}

#include <vector>
#include <list>
#include <iostream>

template <class Type, size_t N>
size_t arraySize(Type const (&)[N])
{
return N;
}

void string_test()
{
string const array[] = { "Hello", "cool", "world" };
vector<string> words(array, array + arraySize(array ));
cout << to_string(words , string(" ")) << "!\n";
}

void int_test()
{
int const array[] = { 1, 7, 42, 100 };
vector<int> numbers(array, array + arraySize(array ));
cout << to_string(numbe rs, " + ") << '\n';
}

void empty_test()
{
list<double> doubles;
cout << "Empty: " << to_string(doubl es, " - ") << '\n';
}

int main()
{
string_test();
int_test();
empty_test();
}

Ali
Jul 22 '05 #4
ma*******@gmx.d e (Markus Dehmann) wrote in message news:<c1******* *************** ****@posting.go ogle.com>...
I am wondering what is the "best" code to print out the elements of a
vector.
Assume they contain strings.

With "best", I mean shortest and most readable at the same time.

Of course, a for loop can be done. But I guess one can do it more
elegantly.
Something like this would be possible:

copy(v.begin(), v.end(), ostream_iterato r<string>(cout , "\n"));

This is as good as it gets. There ain't nothin better.
But I don't like it: The line begins with "copy", and that's
confusing. It has a kind of misleading semantics.

Then better with for_each. How would that look like? Or is there a
better version?

I wonder why there is no to_string(const string& delimiter) function
in vector. Then, we could write:

cout << v.to_string("\n ") << endl;


This method would be intrinsically less efficient. It would be
dynamically filling and resizing a string, then pumping it to cout in
one shot. A slow down would be noticeable if the vector were very
large.

Whereas even with a very large array, the copy() approach would be
efficient with less memory overhead.
Jul 22 '05 #5

"Markus Dehmann" <ma*******@gmx. de> wrote in message
news:c1******** *************** ***@posting.goo gle.com...
I am wondering what is the "best" code to print out the elements of a
vector.
Assume they contain strings.

With "best", I mean shortest and most readable at the same time.

Of course, a for loop can be done. But I guess one can do it more
elegantly.
Something like this would be possible:

copy(v.begin(), v.end(), ostream_iterato r<string>(cout , "\n"));

But I don't like it: The line begins with "copy", and that's
confusing. It has a kind of misleading semantics.


In the end, the for loop is probably the most readable, and it's only
slightly more verbose. But beauty is in the eye of the beholder, so I'm
sure others find the ostream_iterato r version readable. If you want a
one-line method for displaying the contents of a container that avoids
"misleading semantics", then you could write a trivial function.

template <class T>
void display_contain er( const T& v ) {
// display elements using method of choice
std::copy(v.beg in(), v.end(), std::ostream_it erator<typename
T::value_type>( std::cout, "\n"));
}

int main() {
std::vector<int > v;
// ...
display_contain er(v);
}

--
David Hilsee
Jul 22 '05 #6
"Jeff" <su********@gma il.com> wrote in message
ma*******@gmx.d e (Markus Dehmann) wrote in message

cout << v.to_string("\n ") << endl;


This method would be intrinsically less efficient. It would be
dynamically filling and resizing a string, then pumping it to cout in
one shot. A slow down would be noticeable if the vector were very
large.

Whereas even with a very large array, the copy() approach would be
efficient with less memory overhead.


Not necessarily. If v.to_string(v) or to_string(v) returns a proxy object,
then we can overload ostream's operator<< to print the vector elements to
the stream directly. The proxy object would store a pointer to the vector
along with the delimeter character. It's syntactic sugar for the same old
loop or std::copy thing.
Jul 22 '05 #7
Markus Dehmann wrote:
copy(v.begin(), v.end(), ostream_iterato r<string>(cout , "\n"));

Then better with for_each. How would that look like?


That is an interesting question. I don't know any way to do this without
writing your own class:

struct print {
ostream& out;
print(ostream& os): out(os) {}
template <typename T>
void operator()(T const& x){ out << x; }
};

(I removed the delimiter to simplify the example)

It should have been possible to create the object print(cout) using only
the functional capabilities of c++, but bind1st accepts only const
arguments so it cannot be used to bind cout as the first argument of <<
or ostream_iterato r<string>(cout ) as the first argument of =.

bind1st(mem_fun _ref<ostream&,o stream,T>(&ostr eam::operator<< ),cout)
would be nice if it worked, wouldn't it? (no working around the fact
that you have to explicit the template arguments for an overloaded
function, it seems)

Or (where typ stands for ostream_iterato r<T>):
bind1st(mem_fun _ref<typ&,typ,c onst T&>(&typ::opera tor=),typ(cout) )

I hope some day something similar will be possible... (bind1st is not
the only thing that prevents the second exemple from working as is, also
bind1st_ref and allowing reference to reference would be enough for the
first one)
Jul 22 '05 #8
Markus,

"Markus Dehmann" <ma*******@gmx. de> wrote in message
news:c1******** *************** ***@posting.goo gle.com...
I am wondering what is the "best" code to print out the elements of a
vector.
Assume they contain strings.

With "best", I mean shortest and most readable at the same time.

Of course, a for loop can be done. But I guess one can do it more
elegantly.
Something like this would be possible:

copy(v.begin(), v.end(), ostream_iterato r<string>(cout , "\n"));

But I don't like it: The line begins with "copy", and that's
confusing. It has a kind of misleading semantics.
Agreed, and forces one to play games if a different terminating delimiter is
desired.
Then better with for_each. How would that look like? Or is there a
better version?

I wonder why there is no to_string(const string& delimiter) function
in vector. Then, we could write:

cout << v.to_string("\n ") << endl;
How about something like:

std::cout << range_stream( v.begin(), v.end(), "{ ", ", " " }\n" );
With the following definition of range_stream:

#if !defined(RangeS treamerHeaderIn cluded)
#define RangeStreamerHe aderIncluded

template< class tItr, class tDBeg, class tDInner, class tDEnd > class
range_streamer
{
tItr mBeg;
tItr mEnd;
tDBeg mDBeg;
tDInner mDInner;
tDEnd mDEnd;
public:
range_streamer( tItr aBeg, tItr aEnd, tDBeg aDBeg, tDInner aDInner, tDEnd
aDEnd )
: mBeg ( aBeg )
, mEnd ( aEnd )
, mDBeg ( aDBeg )
, mDInner( aDInner )
, mDEnd ( aDEnd )
{}

template< class tStream >
void OutputTo( tStream& s )const
{
if( mBeg != mEnd )
{
tItr lItr = mBeg;

s << mDBeg << *lItr;

for( ++lItr ; lItr != mEnd ; ++lItr )
{
s << mDInner << *lItr;
}
s << mDEnd;
}
}
};

template< class tItr, class tDBeg, class tDInner, class tDEnd >
inline range_streamer< tItr,tDBeg,tDIn ner,tDEnd>
range_stream( tItr aBeg, tItr aEnd, tDBeg aDBeg, tDInner aDInner, tDEnd
aDEnd )
{
return range_streamer< tItr,tDBeg,tDIn ner,tDEnd>( aBeg, aEnd, aDBeg,
aDInner, aDEnd );
}

template< class tStream, class tItr, class tDBeg, class tDInner, class tDEnd

inline tStream& operator<<( tStream& s, const
range_streamer< tItr,tDBeg,tDIn ner,tDEnd>& aRS )
{
aRS.OutputTo(s) ;

return s;
}

#endif //RangeStreamerHe aderIncluded
Jul 22 '05 #9

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

Similar topics

4
2533
by: Shailesh | last post by:
Hi! I want to overload << operator so that it can print an arry defined in MyClass.My problem is that I want to print only a no of elements NOT all the elements in the array and this no of elements depends upon user input.The code below describes this in detail: class MyClass { public: unsigned short x;
8
2217
by: Generic Usenet Account | last post by:
To settle the dispute regarding what happens when an "erase" method is invoked on an STL container (i.e. whether the element is merely removed from the container or whether it also gets deleted in the process), I looked up the STL code. Erase certainly does not delete the memory associated with the element. However, it appears that the destructor on the element is invoked. I wonder why it has to be this way. In my opinion, this renders...
6
8030
by: Jason Heyes | last post by:
What is a good way of removing elements from std::vector so that the elements removed satisfy a predicate and end up stored in another std::vector. It seems as though the algorithm std::remove_if only achieves half the job. Here is how I would use std::remove_if to remove elements from std::vector based on predicate: v.erase(std::remove_if(v.begin(), v.end(), pred), v.end()); After that line is executed I cannot get back the elements...
6
3129
by: Matthias | last post by:
Hi, say I have a vector v1: std::vector<SomeType> v1; and I need a vector v2 of pointers to v1's elements: std::vector<SomeType*> v2;
34
4184
by: Adam Hartshorne | last post by:
Hi All, I have the following problem, and I would be extremely grateful if somebody would be kind enough to suggest an efficient solution to it. I create an instance of a Class A, and "push_back" a copy of this into a vector V. This is repeated many times in an iterative process. Ok whenever I "push_back" a copy of Class A, I also want to assign a pointer contained in an exisiting instance of a Class B to this
11
2750
by: koperenkogel | last post by:
Dear cpp-ians, I am working with a vector of structures. vector <meta_segment> meta_segm (2421500); and the structure look like: struct meta_segment { float id; float num;
9
3615
by: david wolf | last post by:
I want to delete all even numbers in a vector, I am not sure if there's any better way to do it. Following program is how I did it. Look at the part of code beginning from comments: //delete all even numbers. My questions is actullay I have to put pos++ in the body of the loop(also in if, else, statement). Can I somehow put it in for(...;...;...). Or can I use index instead of iterator in order to delete elements from
8
10954
by: cayblood | last post by:
Hello, I have been interested in something kind of like the next_permutation from the STL algorithm library, except that I want it to find possible combinations of vector elements. Here is a more detailed example of what I want: Given a vector containing an arbitrary number of vectors, each of which contains an arbitrary number of elements, generate a new vector in which each element consists of one element taken from its corresponding...
4
2475
by: Christian Bruckhoff | last post by:
Hi. Is there a possibility to delete elements out of a vector? At the moment i do it by copying all needed elements to another vector. After clearing the old vector i copy them back element by element. Regards! Christian
0
9584
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,...
0
10583
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10337
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10082
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
9160
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
7622
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
6854
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5525
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...
1
4301
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

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.