473,418 Members | 2,029 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,418 software developers and data experts.

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_iterator<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 25412

"Markus Dehmann" <ma*******@gmx.de> wrote in message
news:c1**************************@posting.google.c om...
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_iterator<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_iterator<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(Collection const & collection,
char const * delimiter)
{
typedef typename Collection::const_iterator Iter;

Iter beg = collection.begin();
Iter const end = collection.end();

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

std::ostringstream os;

os << *beg;
++beg;

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

return os.str();
}

template<class Collection>
string to_string(Collection const & collection,
string const & delimiter)
{
return to_string(collection, 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(numbers, " + ") << '\n';
}

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

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

Ali
Jul 22 '05 #4
ma*******@gmx.de (Markus Dehmann) wrote in message news:<c1**************************@posting.google. 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_iterator<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.google.c om...
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_iterator<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_iterator 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_container( const T& v ) {
// display elements using method of choice
std::copy(v.begin(), v.end(), std::ostream_iterator<typename
T::value_type>(std::cout, "\n"));
}

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

--
David Hilsee
Jul 22 '05 #6
"Jeff" <su********@gmail.com> wrote in message
ma*******@gmx.de (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_iterator<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_iterator<string>(cout) as the first argument of =.

bind1st(mem_fun_ref<ostream&,ostream,T>(&ostream:: 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_iterator<T>):
bind1st(mem_fun_ref<typ&,typ,const T&>(&typ::operator=),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.google.c om...
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_iterator<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(RangeStreamerHeaderIncluded)
#define RangeStreamerHeaderIncluded

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,tDInner,tDEnd>
range_stream( tItr aBeg, tItr aEnd, tDBeg aDBeg, tDInner aDInner, tDEnd
aDEnd )
{
return range_streamer<tItr,tDBeg,tDInner,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,tDInner,tDEnd>& aRS )
{
aRS.OutputTo(s);

return s;
}

#endif //RangeStreamerHeaderIncluded
Jul 22 '05 #9

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

Similar topics

4
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...
8
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...
6
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...
6
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
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...
11
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
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...
8
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...
4
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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,...
0
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...

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.