Related
I know how to do this in other languages, but not in C++, which I am forced to use here.
I have a set of strings (keywords) that I'm printing to out as a list, and the strings need a comma between them, but not a trailing comma. In Java, for instance, I would use a StringBuilder and just delete the comma off the end after I've built my string. How can I do it in C++?
auto iter = keywords.begin();
for (iter; iter != keywords.end( ); iter++ )
{
out << *iter << ", ";
}
out << endl;
I initially tried inserting the following block to do it (moving the comma printing here):
if (iter++ != keywords.end())
out << ", ";
iter--;
Use an infix_iterator:
// infix_iterator.h
//
// Lifted from Jerry Coffin's 's prefix_ostream_iterator
#if !defined(INFIX_ITERATOR_H_)
#define INFIX_ITERATOR_H_
#include <ostream>
#include <iterator>
template <class T,
class charT=char,
class traits=std::char_traits<charT> >
class infix_ostream_iterator :
public std::iterator<std::output_iterator_tag,void,void,void,void>
{
std::basic_ostream<charT,traits> *os;
charT const* delimiter;
bool first_elem;
public:
typedef charT char_type;
typedef traits traits_type;
typedef std::basic_ostream<charT,traits> ostream_type;
infix_ostream_iterator(ostream_type& s)
: os(&s),delimiter(0), first_elem(true)
{}
infix_ostream_iterator(ostream_type& s, charT const *d)
: os(&s),delimiter(d), first_elem(true)
{}
infix_ostream_iterator<T,charT,traits>& operator=(T const &item)
{
// Here's the only real change from ostream_iterator:
// Normally, the '*os << item;' would come before the 'if'.
if (!first_elem && delimiter != 0)
*os << delimiter;
*os << item;
first_elem = false;
return *this;
}
infix_ostream_iterator<T,charT,traits> &operator*() {
return *this;
}
infix_ostream_iterator<T,charT,traits> &operator++() {
return *this;
}
infix_ostream_iterator<T,charT,traits> &operator++(int) {
return *this;
}
};
#endif
Usage would be something like:
#include "infix_iterator.h"
// ...
std::copy(keywords.begin(), keywords.end(), infix_iterator(out, ","));
In an experimental C++17 ready compiler coming soon to you, you can use std::experimental::ostream_joiner:
#include <algorithm>
#include <experimental/iterator>
#include <iostream>
#include <iterator>
int main()
{
int i[] = {1, 2, 3, 4, 5};
std::copy(std::begin(i),
std::end(i),
std::experimental::make_ostream_joiner(std::cout, ", "));
}
Live examples using GCC 6.0 SVN and Clang 3.9 SVN
Because everyone has decided to do this with while loops, I'll give an example with for loops.
for (iter = keywords.begin(); iter != keywords.end(); iter++) {
if (iter != keywords.begin()) cout << ", ";
cout << *iter;
}
Assuming a vaguely normal output stream, so that writing an empty string to it does indeed do nothing:
const char *padding = "";
for (auto iter = keywords.begin(); iter != keywords.end(); ++iter) {
out << padding << *iter;
padding = ", "
}
One common approach is to print the first item prior to the loop, and loop only over the remaining items, PRE-printing a comma before each remaining item.
Alternately you should be able to create your own stream that maintains a current state of the line (before endl) and puts commas in the appropriate place.
EDIT:
You can also use a middle-tested loop as suggested by T.E.D. It would be something like:
if(!keywords.empty())
{
auto iter = keywords.begin();
while(true)
{
out << *iter;
++iter;
if(iter == keywords.end())
{
break;
}
else
{
out << ", ";
}
}
}
I mentioned the "print first item before loop" method first because it keeps the loop body really simple, but any of the approaches work fine.
There are lots of clever solutions, and too many that mangle the code beyond hope of salvation without letting the compiler do its job.
The obvious solution, is to special-case the first iteration:
bool first = true;
for (auto const& e: sequence) {
if (first) { first = false; } else { out << ", "; }
out << e;
}
It's a dead simple pattern which:
Does not mangle the loop: it's still obvious at a glance that each element will be iterated on.
Allows more than just putting a separator, or actually printing a list, as the else block and the loop body can contain arbitrary statements.
It may not be the absolutely most efficient code, but the potential performance loss of a single well-predicted branch is very likely to be overshadowed by the massive behemoth that is std::ostream::operator<<.
Something like this?
while (iter != keywords.end())
{
out << *iter;
iter++;
if (iter != keywords.end()) cout << ", ";
}
My typical method for doing separators (in any language) is to use a mid-tested loop. The C++ code would be:
for (;;) {
std::cout << *iter;
if (++iter == keywords.end()) break;
std::cout << ",";
}
(note: An extra if check is needed prior to the loop if keywords may be empty)
Most of the other solutions shown end up doing an entire extra test every loop iteration. You are doing I/O, so the time taken by that isn't a huge problem, but it offends my sensibilities.
In python we just write:
print ", ".join(keywords)
so why not:
template<class S, class V>
std::string
join(const S& sep, const V& v)
{
std::ostringstream oss;
if (!v.empty()) {
typename V::const_iterator it = v.begin();
oss << *it++;
for (typename V::const_iterator e = v.end(); it != e; ++it)
oss << sep << *it;
}
return oss.str();
}
and then just use it like:
cout << join(", ", keywords) << endl;
Unlike in the python example above where the " " is a string and the keywords has to be an iterable of strings, here in this C++ example the separator and keywords can be anything streamable, e.g.
cout << join('\n', keywords) << endl;
I suggest you simply switch the first character with the help of a lambda.
std::function<std::string()> f = [&]() {f = [](){ return ","; }; return ""; };
for (auto &k : keywords)
std::cout << f() << k;
Try this:
typedef std::vector<std::string> Container;
typedef Container::const_iterator CIter;
Container data;
// Now fill the container.
// Now print the container.
// The advantage of this technique is that ther is no extra test during the loop.
// There is only one additional test !test.empty() done at the beginning.
if (!data.empty())
{
std::cout << data[0];
for(CIter loop = data.begin() + 1; loop != data.end(); ++loop)
{
std::cout << "," << *loop;
}
}
to avoid placing an if inside the loop, I use this:
vector<int> keywords = {1, 2, 3, 4, 5};
if (!keywords.empty())
{
copy(keywords.begin(), std::prev(keywords.end()),
std::ostream_iterator<int> (std::cout,", "));
std::cout << keywords.back();
}
It depends on the vector type, int, but you can remove it with some helper.
If the values are std::strings you can write this nicely in a declarative style with range-v3
#include <range/v3/all.hpp>
#include <vector>
#include <iostream>
#include <string>
int main()
{
using namespace ranges;
std::vector<std::string> const vv = { "a","b","c" };
auto joined = vv | view::join(',');
std::cout << to_<std::string>(joined) << std::endl;
}
For other types which have to be converted to string you can just add a transformation calling to_string.
#include <range/v3/all.hpp>
#include <vector>
#include <iostream>
#include <string>
int main()
{
using namespace ranges;
std::vector<int> const vv = { 1,2,3 };
auto joined = vv | view::transform([](int x) {return std::to_string(x);})
| view::join(',');
std::cout << to_<std::string>(joined) << std::endl;
}
There is a little problem with the ++ operator you are using.
You can try:
if (++iter != keywords.end())
out << ", ";
iter--;
This way, ++ will be evaluated before compare the iterator with keywords.end().
I use a little helper class for that:
class text_separator {
public:
text_separator(const char* sep) : sep(sep), needsep(false) {}
// returns an empty string the first time it is called
// returns the provided separator string every other time
const char* operator()() {
if (needsep)
return sep;
needsep = true;
return "";
}
void reset() { needsep = false; }
private:
const char* sep;
bool needsep;
};
To use it:
text_separator sep(", ");
for (int i = 0; i < 10; ++i)
cout << sep() << i;
Another possible solution, which avoids an if
Char comma = '[';
for (const auto& element : elements) {
std::cout.put(comma) << element;
comma = ',';
}
std::cout.put(']');
Depends what you're doing in your loop.
Following should do:-
const std::vector<__int64>& a_setRequestId
std::stringstream strStream;
std::copy(a_setRequestId.begin(), a_setRequestId.end() -1, std::ostream_iterator<__int64>(strStream, ", "));
strStream << a_setRequestId.back();
I think this variant of #MarkB's answer strikes optimal balance of readability, simplicity and terseness:
auto iter= keywords.begin();
if (iter!=keywords.end()) {
out << *iter;
while(++iter != keywords.end())
out << "," << *iter;
}
out << endl;
It's very easy to fix that (taken from my answer here):
bool print_delim = false;
for (auto iter = keywords.begin(); iter != keywords.end( ); iter++ ) {
if(print_delim) {
out << ", ";
}
out << *iter;
print_delim = true;
}
out << endl;
I am using this idiom (pattern?) in many programming languages, and all kind of tasks where you need to construct delimited output from list like inputs. Let me give the abstract in pseudo code:
empty output
firstIteration = true
foreach item in list
if firstIteration
add delimiter to output
add item to output
firstIteration = false
In some cases one could even omit the firstIteration indicator variable completely:
empty output
foreach item in list
if not is_empty(output)
add delimiter to output
add item to output
I think simplicity is better for me, so after I look through all answers I prepared my solution(c++14 required):
#include <iostream>
#include <vector>
#include <utility> // for std::exchange c++14
int main()
{
std::vector nums{1, 2, 3, 4, 5}; // c++17
const char* delim = "";
for (const auto value : nums)
{
std::cout << std::exchange(delim, ", ") << value;
}
}
Output example:
1, 2, 3, 4, 5
I think this should work
while (iter != keywords.end( ))
{
out << *iter;
iter++ ;
if (iter != keywords.end( )) out << ", ";
}
Using boost:
std::string add_str("");
const std::string sep(",");
for_each(v.begin(), v.end(), add_str += boost::lambda::ret<std::string>(boost::lambda::_1 + sep));
and you obtain a string containing the vector, comma delimited.
EDIT:
to remove the last comma, just issue:
add_str = add_str.substr(0, add_str.size()-1);
Could be like so..
bool bFirst = true;
for (auto curr = keywords.begin(); curr != keywords.end(); ++curr) {
std::cout << (bFirst ? "" : ", ") << *curr;
bFirst = false;
}
Here are two methods you could use, which are both essentially the same idea. I like these methods because they do not contain any unnecessary conditional checks or assignment operations. I'll call the first one the print first method.
Method 1: the print first method
if (!keywords.empty()) {
out << *(keywords.begin()); // First element.
for (auto it = ++(keywords.begin()); it != keywords.end(); it++)
out << ", " << *it; // Every subsequent element.
}
This is the method I used at first. It works by printing the first element in your container by itself, and then prints every subsequent element preceded by a comma and space. It's simple, concise, and works great if that's all you need it to do. Once you want to do more things, like add an "and" before the last element, this method falls short. You'd have to check each loop iteration for if it's on the last element. Adding a period, or newline after the list wouldn't be so bad, though. You could just add one more line after the for-loop to append whatever you desire to the list.
The second method I like a lot more. That one I'll call the print last method, as it does the same thing as the first but in reverse order.
Method 2: the print last method
if (!keywords.empty()) {
auto it = keywords.begin(), last = std::prev(keywords.end());
for (; it != last; it++) // Every preceding element.
out << *it << ", ";
out << "and " << *it << ".\n"; // Last element.
}
This one works by printing every element except for the last with a comma and space, allowing you to optionally add an "and" before it, a period after it, and/or a newline character. As you can see, this method gives you a lot more options on how you can handle that last element without affecting the performance of the loop or adding much code.
If it bothers you to leave the first part of the for-loop empty, you could write it like so:
if (!keywords.empty()) {
auto it, last;
for (it = keywords.begin(), last = std::prev(keywords.end()); it != last; it++)
out << *it << ", ";
out << "and " << *it << ".\n";
}
I would go with something like this, an easy solution and should work for all iterators.
int maxele = maxele = v.size() - 1;
for ( cur = v.begin() , i = 0; i < maxele ; ++i)
{
std::cout << *cur++ << " , ";
}
if ( maxele >= 0 )
{
std::cout << *cur << std::endl;
}
You can use a do loop, rewrite the loop condition for the first iteration, and use the short-circuit && operator and the fact that a valid stream is true.
auto iter = keywords.begin();
if ( ! keywords.empty() ) do {
out << * iter;
} while ( ++ iter != keywords.end() && out << ", " );
out << endl;
This one overloads the stream operator. Yes global variables are evil.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
int index = 0;
template<typename T, template <typename, typename> class Cont>
std::ostream& operator<<(std::ostream& os, const Cont<T, std::allocator<T>>& vec)
{
if (index < vec.size()) {
if (index + 1 < vec.size())
return os << vec[index++] << "-" << vec;
else
return os << vec[index++] << vec;
} else return os;
}
int main()
{
std::vector<int> nums(10);
int n{0};
std::generate(nums.begin(), nums.end(), [&]{ return n++; });
std::cout << nums << std::endl;
}
Can use functors:
#include <functional>
string getSeparatedValues(function<bool()> condition, function<string()> output, string separator)
{
string out;
out += output();
while (condition())
out += separator + output();
return out;
}
Example:
if (!keywords.empty())
{
auto iter = keywords.begin();
cout << getSeparatedValues([&]() { return ++iter != keywords.end(); }, [&]() { return *iter; }, ", ") << endl;
}
A combination of c++11 lambda and macro:
#define INFIX_PRINTER(os, sep)([&]()->decltype(os)&{static int f=1;os<<(f?(f=0,""):sep);return os;})()
Usage:
for(const auto& k: keywords)
INFIX_PRINTER(out, ", ") << k;
I like a range-based for with a is_last_elem test. That imho it's very readable:
for (auto& e : range)
{
if (!is_last_elem(e, range)) [[likely]]
os << e << ", ";
else
os << e;
}
os << std::endl;
Full code:
C++20:
#include <iostream>
#include <list>
#include <ranges>
#include <utility>
#include <type_traits>
#include <memory>
template <std::ranges::bidirectional_range R>
bool is_last_elem(const std::ranges::range_value_t<R>& elem, const R& range)
{
auto last_it = range.end();
std::advance(last_it, -1);
return std::addressof(elem) == std::addressof(*last_it);
}
template <std::ranges::bidirectional_range R, class Stream = std::ostream>
void print(const R& range, std::ostream& os = std::cout)
{
for (auto& e : range)
{
if (!is_last_elem(e, range)) [[likely]]
os << e << ", ";
else
os << e;
}
os << std::endl;
}
int main()
{
std::list<int> v{1, 2, 3, 4, 5};
print(v);
}
C++17:
#include <iostream>
#include <list>
#include <utility>
#include <type_traits>
#include <memory>
template <class Range>
using value_type_t = std::remove_reference_t<decltype(*std::begin(std::declval<Range>()))>;
template <class Range>
bool is_last_elem(const value_type_t<Range>& elem, const Range& range)
{
auto last_it = range.end();
std::advance(last_it, -1);
return std::addressof(elem) == std::addressof(*last_it);
}
template <class Range, class Stream = std::ostream>
void print(const Range& range, std::ostream& os = std::cout)
{
for (auto& e : range)
{
if (!is_last_elem(e, range))
os << e << ", ";
else
os << e;
}
os << std::endl;
}
int main()
{
std::list<int> v{1, 2, 3, 4, 5};
print(v);
}
Consider following code:
#include <iostream>
#include <list>
#include <memory>
class Foo;
class Foo {
public:
Foo(int i): id(i) {}
typename std::list<std::shared_ptr<Foo>>::iterator i2;
int id;
};
int main() {
std::list<std::shared_ptr<Foo>> l;
auto f1 = std::make_shared<Foo>(1);
f1->i2 = l.end();
l.insert(f1->i2, f1);
std::cout << f1->id << std::endl;
std::cout << l.size() << std::endl;
for (auto i: l) {
std::cout << i->id << std::endl;
}
auto t = f1->i2;
l.erase(t);
std::cout << l.size() << std::endl;
}
Executing these code will get an SIGSEGV at l.erase(t),seems ListNode were destroyed before shared_ptr decrease its ref_count. Why?How to fix it?
After insert your f1->i2 left l.end(). You try to erase l.end(), that is not allowed.
Fix is simple. Change the line where insert called:
f1->i2 = l.insert(f1->i2, f1);
Iterator,initialized before insert/remove operation, may be in an indeterminate state after the operation and should be updated again. Also you are trying to delete a node in the list through an iterator which itself is pointing to list.end(). For deleting the last element of a list, you can rather use std::list.pop_back();
auto t = f1->i2;
l.erase(--t); // Change this in your code - decrease the iterator
I have done the programming but it is not reversing. I have used a different map to put the values in reverse order,but it still shows the same. My main question was to traverse backward and print the values using range based loop.
#include "stdafx.h"
#include <iostream>
#include<conio.h>
#include <stdio.h>
#include<vector>
#include<map>
#include<utility>
#include<set>
map<int, int>m1;
for (int i = 1; i <= 100; ++i)
{
m1.insert({ i,i });
}
for (const auto &y :m1)
{
cout <<"("<< y.first << " "<<y.second << ")" <<" " ;
}
cout << endl << endl;
map<int, int>m2;
map<int, int>::reverse_iterator iter;
for (auto iter = m1.rbegin(); iter != m1.rend(); ++iter)
{
m2.insert({ iter->first,iter->second });
}
for (const auto &y : m2)
{
cout << "(" << y.first << " " << y.second << ")" << " ";
}
As Some Programmer Dude pointed out, but for the completeness of my answer, a std::map is sorted on the key, no matter what order you insert the elements. One option would be to create a new map with the opposite sorting, but that doesn't seem to be what you really want.
It seems you know how about reverse iterators, but not how to get at them when using range-based for. Since it operates on a range, i.e. some type that provides begin and end iterators, you need to create some wrapper around your map that provides this.
Here's a general one I just put together than works in C++11. It won't cover every possible case, and can be made a bit neater in C++14, but it will work for you.
#include <iostream>
#include <iterator>
// The wrapper type that does reversal
template <typename Range>
class Reverser {
Range& r_;
public:
using iterator_type = std::reverse_iterator<decltype(std::begin(r_))>;
Reverser(Range& r) : r_(r) {}
iterator_type begin() { return iterator_type(std::end(r_)); }
iterator_type end() { return iterator_type(std::begin(r_)); }
};
// Helper creation function
template <typename Range>
Reverser<Range> reverse(Range& r)
{
return Reverser<Range>(r);
}
int main()
{
int vals[] = {1, 2, 3, 4, 5};
for (auto i : reverse(vals))
std::cout << i << '\n';
}
This outputs:
$ ./reverse
5
4
3
2
1
(You may also find libraries that provide a similar adapter; Eric Niebler is working on a ranges library for The Standard.)
Also, please reconsider your use of what are often considered bad practices: using namespace std; and endl (those are links to explanations).
Here's an example of iterating backward through a std::map:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<int, int> m;
m[1] = 1;
m[2] = 2;
m[3] = 3;
for (auto iter = m.rbegin(); iter != m.rend(); ++iter) {
std::cout << iter->first << ": " << iter->second << std::endl;
}
}
If you are pre-C++11, you'll just need to spell out auto, which is:
std::map<int, int>::reverse_iterator
If you're using boost, you can use a range-based for loop with a reverse adapter:
#include <boost/range/adaptor/reversed.hpp>
for (auto& iter : boost::adaptors::reverse(m)) {
std::cout << iter.first << ": " << iter.second << std::endl;
}
If you only need to print the elements in the map in reverse order,you don't need another map for it,you can do this:
std::map<int, int>::reverse_iterator iter;
for (iter = m1.rbegin(); iter != m1.rend(); ++iter)
{
std::cout << "(" << iter->first << " " << iter->second << ")" << " ";
}
I'm new to C++, and am trying to implement the Selection Sort Algorithm as an exercise.
I've gotten as far as trying to swap the value in the left-most memory location with the value in the memory location of the minimum of the unsorted portion of the vector.
( See the code below. )
Is it possible to use std::vector::iterator's to alter the values contained in the vector it belongs to?
#include <vector>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
template<typename T>
ostream& operator<<( ostream& out, vector<T> thisVector ) {
for( size_t i = 0, choke = thisVector.size(); i < choke; i++ )
out << thisVector[ i ] << " ";
return out;
}
template<typename T>
typename vector<T>::iterator get_minimum( vector<T>& thisVector, typename vector<T>::iterator pos, typename vector<T>::iterator end ) {
T min = *pos;
typename vector<T>::iterator minPos;
while ( pos != end ) {
if ( *pos < min ) {
min = *pos;
minPos = pos;
}
pos++;
}
return minPos;
}
template<typename T>
void swap( typename vector<T>::iterator pos, typename vector<T>::iterator& minPos ) {
T temp = *pos;
// I was hoping the following two lines would modify the vector passed to selection_sort
pos = *minPos;
minPos = temp;
return;
}
template<typename T>
void selection_sort( vector<T>& thisVector, typename vector<T>::iterator pos ) {
typename vector<T>::iterator end = thisVector.end();
typename vector<T>::iterator minPos = get_minimum( thisVector, pos, end );
cout << "Swap was given this " << *pos << " " << *minPos << endl;
swap( pos, minPos );
cout << "and returned this " << *pos << " " << *minPos << endl;
return;
}
int main() {
// initialize random seed
srand (time(NULL));
// Create data stub
vector<int> myThing;
do {
myThing.push_back( rand() % 20 );
} while ( myThing.size() <= 10 );
cout << "Unsorted: " << myThing << endl;
selection_sort( myThing, myThing.begin() );
cout << " Sorted: " << myThing << endl;
return 0;
}
Yes, it is possible. Given an iterator iter, *iter can be assigned to like a normal lvalue to modify the underlying container, e.g.:
*iter = 5; // The value in the container that `iter` points to is now 5.
It is possible. And here is a trick to make your life easier.
Swap is already a defined function.
Add #include <utility> and you get swap for free. Many C++ objects define swap specializations. For example, std::vector implements a swap between two vectors by simply swapping the pointers.
For your code you can remove your definition of swap and use swap(*pos, *minPos)
The problem that you are facing with swapping the values the iterators point to is caused by the fact that the compiler picks up std::swap by using ADL. std::swap just swaps where the iterators point to but not the values the iterators point to.
If you name the function myswap and call myswap instead of swap, you are probably going to see compiler error messages. Check out my question on the subject.
Instead, if you use:
template<typename Iterator>
void myswap(Iterator pos1,
Iterator pos2)
{
auto temp = *pos1;
*pos1 = *pos2;
*pos2 = temp;
}
everything should work. Here's a working program, using g++ 4.8.2.
#include <iostream>
#include <vector>
#include <iterator>
template<typename Iterator>
void myswap(Iterator pos1, Iterator pos2)
{
auto temp = *pos1;
*pos1 = *pos2;
*pos2 = temp;
}
void testMyswap()
{
std::cout << "\nTesting myswap()\n";
std::vector<int> v{1, 2, 3, 4, 5, 6};
std::vector<int>::iterator iter = v.begin();
std::vector<int>::iterator temp = std::next(iter, 2);
std::cout << "Values iterators point to before swap.\n";
std::cout << *iter << " " << *temp << std::endl;
myswap(iter, temp);
std::cout << "Values iterators point to after swap.\n";
std::cout << *iter << " " << *temp << std::endl;
std::cout << "The vector after the swap.\n";
for ( iter = v.begin(); iter != v.end(); ++iter )
{
std::cout << *iter << " ";
}
std::cout << std::endl;
}
int main()
{
testMyswap();
return 0;
}
Output
Testing myswap()
Values iterators point to before swap.
1 3
Values iterators point to after swap.
3 1
The vector after the swap.
3 2 1 4 5 6
I needed to namesapce my code: being a very new newbie, I hadn't realized std::swap(iter, iter) already exists, and was being called--rather than my swap function.
Nonetheless, once I namespaced my code, jwodder's response proved to do the trick: by using *iter rather than iter, my code compiled and the vector was properly modified by swap.
I know how to do this in other languages, but not in C++, which I am forced to use here.
I have a set of strings (keywords) that I'm printing to out as a list, and the strings need a comma between them, but not a trailing comma. In Java, for instance, I would use a StringBuilder and just delete the comma off the end after I've built my string. How can I do it in C++?
auto iter = keywords.begin();
for (iter; iter != keywords.end( ); iter++ )
{
out << *iter << ", ";
}
out << endl;
I initially tried inserting the following block to do it (moving the comma printing here):
if (iter++ != keywords.end())
out << ", ";
iter--;
Use an infix_iterator:
// infix_iterator.h
//
// Lifted from Jerry Coffin's 's prefix_ostream_iterator
#if !defined(INFIX_ITERATOR_H_)
#define INFIX_ITERATOR_H_
#include <ostream>
#include <iterator>
template <class T,
class charT=char,
class traits=std::char_traits<charT> >
class infix_ostream_iterator :
public std::iterator<std::output_iterator_tag,void,void,void,void>
{
std::basic_ostream<charT,traits> *os;
charT const* delimiter;
bool first_elem;
public:
typedef charT char_type;
typedef traits traits_type;
typedef std::basic_ostream<charT,traits> ostream_type;
infix_ostream_iterator(ostream_type& s)
: os(&s),delimiter(0), first_elem(true)
{}
infix_ostream_iterator(ostream_type& s, charT const *d)
: os(&s),delimiter(d), first_elem(true)
{}
infix_ostream_iterator<T,charT,traits>& operator=(T const &item)
{
// Here's the only real change from ostream_iterator:
// Normally, the '*os << item;' would come before the 'if'.
if (!first_elem && delimiter != 0)
*os << delimiter;
*os << item;
first_elem = false;
return *this;
}
infix_ostream_iterator<T,charT,traits> &operator*() {
return *this;
}
infix_ostream_iterator<T,charT,traits> &operator++() {
return *this;
}
infix_ostream_iterator<T,charT,traits> &operator++(int) {
return *this;
}
};
#endif
Usage would be something like:
#include "infix_iterator.h"
// ...
std::copy(keywords.begin(), keywords.end(), infix_iterator(out, ","));
In an experimental C++17 ready compiler coming soon to you, you can use std::experimental::ostream_joiner:
#include <algorithm>
#include <experimental/iterator>
#include <iostream>
#include <iterator>
int main()
{
int i[] = {1, 2, 3, 4, 5};
std::copy(std::begin(i),
std::end(i),
std::experimental::make_ostream_joiner(std::cout, ", "));
}
Live examples using GCC 6.0 SVN and Clang 3.9 SVN
Because everyone has decided to do this with while loops, I'll give an example with for loops.
for (iter = keywords.begin(); iter != keywords.end(); iter++) {
if (iter != keywords.begin()) cout << ", ";
cout << *iter;
}
Assuming a vaguely normal output stream, so that writing an empty string to it does indeed do nothing:
const char *padding = "";
for (auto iter = keywords.begin(); iter != keywords.end(); ++iter) {
out << padding << *iter;
padding = ", "
}
One common approach is to print the first item prior to the loop, and loop only over the remaining items, PRE-printing a comma before each remaining item.
Alternately you should be able to create your own stream that maintains a current state of the line (before endl) and puts commas in the appropriate place.
EDIT:
You can also use a middle-tested loop as suggested by T.E.D. It would be something like:
if(!keywords.empty())
{
auto iter = keywords.begin();
while(true)
{
out << *iter;
++iter;
if(iter == keywords.end())
{
break;
}
else
{
out << ", ";
}
}
}
I mentioned the "print first item before loop" method first because it keeps the loop body really simple, but any of the approaches work fine.
There are lots of clever solutions, and too many that mangle the code beyond hope of salvation without letting the compiler do its job.
The obvious solution, is to special-case the first iteration:
bool first = true;
for (auto const& e: sequence) {
if (first) { first = false; } else { out << ", "; }
out << e;
}
It's a dead simple pattern which:
Does not mangle the loop: it's still obvious at a glance that each element will be iterated on.
Allows more than just putting a separator, or actually printing a list, as the else block and the loop body can contain arbitrary statements.
It may not be the absolutely most efficient code, but the potential performance loss of a single well-predicted branch is very likely to be overshadowed by the massive behemoth that is std::ostream::operator<<.
Something like this?
while (iter != keywords.end())
{
out << *iter;
iter++;
if (iter != keywords.end()) cout << ", ";
}
My typical method for doing separators (in any language) is to use a mid-tested loop. The C++ code would be:
for (;;) {
std::cout << *iter;
if (++iter == keywords.end()) break;
std::cout << ",";
}
(note: An extra if check is needed prior to the loop if keywords may be empty)
Most of the other solutions shown end up doing an entire extra test every loop iteration. You are doing I/O, so the time taken by that isn't a huge problem, but it offends my sensibilities.
In python we just write:
print ", ".join(keywords)
so why not:
template<class S, class V>
std::string
join(const S& sep, const V& v)
{
std::ostringstream oss;
if (!v.empty()) {
typename V::const_iterator it = v.begin();
oss << *it++;
for (typename V::const_iterator e = v.end(); it != e; ++it)
oss << sep << *it;
}
return oss.str();
}
and then just use it like:
cout << join(", ", keywords) << endl;
Unlike in the python example above where the " " is a string and the keywords has to be an iterable of strings, here in this C++ example the separator and keywords can be anything streamable, e.g.
cout << join('\n', keywords) << endl;
I suggest you simply switch the first character with the help of a lambda.
std::function<std::string()> f = [&]() {f = [](){ return ","; }; return ""; };
for (auto &k : keywords)
std::cout << f() << k;
Try this:
typedef std::vector<std::string> Container;
typedef Container::const_iterator CIter;
Container data;
// Now fill the container.
// Now print the container.
// The advantage of this technique is that ther is no extra test during the loop.
// There is only one additional test !test.empty() done at the beginning.
if (!data.empty())
{
std::cout << data[0];
for(CIter loop = data.begin() + 1; loop != data.end(); ++loop)
{
std::cout << "," << *loop;
}
}
to avoid placing an if inside the loop, I use this:
vector<int> keywords = {1, 2, 3, 4, 5};
if (!keywords.empty())
{
copy(keywords.begin(), std::prev(keywords.end()),
std::ostream_iterator<int> (std::cout,", "));
std::cout << keywords.back();
}
It depends on the vector type, int, but you can remove it with some helper.
If the values are std::strings you can write this nicely in a declarative style with range-v3
#include <range/v3/all.hpp>
#include <vector>
#include <iostream>
#include <string>
int main()
{
using namespace ranges;
std::vector<std::string> const vv = { "a","b","c" };
auto joined = vv | view::join(',');
std::cout << to_<std::string>(joined) << std::endl;
}
For other types which have to be converted to string you can just add a transformation calling to_string.
#include <range/v3/all.hpp>
#include <vector>
#include <iostream>
#include <string>
int main()
{
using namespace ranges;
std::vector<int> const vv = { 1,2,3 };
auto joined = vv | view::transform([](int x) {return std::to_string(x);})
| view::join(',');
std::cout << to_<std::string>(joined) << std::endl;
}
There is a little problem with the ++ operator you are using.
You can try:
if (++iter != keywords.end())
out << ", ";
iter--;
This way, ++ will be evaluated before compare the iterator with keywords.end().
I use a little helper class for that:
class text_separator {
public:
text_separator(const char* sep) : sep(sep), needsep(false) {}
// returns an empty string the first time it is called
// returns the provided separator string every other time
const char* operator()() {
if (needsep)
return sep;
needsep = true;
return "";
}
void reset() { needsep = false; }
private:
const char* sep;
bool needsep;
};
To use it:
text_separator sep(", ");
for (int i = 0; i < 10; ++i)
cout << sep() << i;
Another possible solution, which avoids an if
Char comma = '[';
for (const auto& element : elements) {
std::cout.put(comma) << element;
comma = ',';
}
std::cout.put(']');
Depends what you're doing in your loop.
Following should do:-
const std::vector<__int64>& a_setRequestId
std::stringstream strStream;
std::copy(a_setRequestId.begin(), a_setRequestId.end() -1, std::ostream_iterator<__int64>(strStream, ", "));
strStream << a_setRequestId.back();
I think this variant of #MarkB's answer strikes optimal balance of readability, simplicity and terseness:
auto iter= keywords.begin();
if (iter!=keywords.end()) {
out << *iter;
while(++iter != keywords.end())
out << "," << *iter;
}
out << endl;
It's very easy to fix that (taken from my answer here):
bool print_delim = false;
for (auto iter = keywords.begin(); iter != keywords.end( ); iter++ ) {
if(print_delim) {
out << ", ";
}
out << *iter;
print_delim = true;
}
out << endl;
I am using this idiom (pattern?) in many programming languages, and all kind of tasks where you need to construct delimited output from list like inputs. Let me give the abstract in pseudo code:
empty output
firstIteration = true
foreach item in list
if firstIteration
add delimiter to output
add item to output
firstIteration = false
In some cases one could even omit the firstIteration indicator variable completely:
empty output
foreach item in list
if not is_empty(output)
add delimiter to output
add item to output
I think simplicity is better for me, so after I look through all answers I prepared my solution(c++14 required):
#include <iostream>
#include <vector>
#include <utility> // for std::exchange c++14
int main()
{
std::vector nums{1, 2, 3, 4, 5}; // c++17
const char* delim = "";
for (const auto value : nums)
{
std::cout << std::exchange(delim, ", ") << value;
}
}
Output example:
1, 2, 3, 4, 5
I think this should work
while (iter != keywords.end( ))
{
out << *iter;
iter++ ;
if (iter != keywords.end( )) out << ", ";
}
Using boost:
std::string add_str("");
const std::string sep(",");
for_each(v.begin(), v.end(), add_str += boost::lambda::ret<std::string>(boost::lambda::_1 + sep));
and you obtain a string containing the vector, comma delimited.
EDIT:
to remove the last comma, just issue:
add_str = add_str.substr(0, add_str.size()-1);
Could be like so..
bool bFirst = true;
for (auto curr = keywords.begin(); curr != keywords.end(); ++curr) {
std::cout << (bFirst ? "" : ", ") << *curr;
bFirst = false;
}
Here are two methods you could use, which are both essentially the same idea. I like these methods because they do not contain any unnecessary conditional checks or assignment operations. I'll call the first one the print first method.
Method 1: the print first method
if (!keywords.empty()) {
out << *(keywords.begin()); // First element.
for (auto it = ++(keywords.begin()); it != keywords.end(); it++)
out << ", " << *it; // Every subsequent element.
}
This is the method I used at first. It works by printing the first element in your container by itself, and then prints every subsequent element preceded by a comma and space. It's simple, concise, and works great if that's all you need it to do. Once you want to do more things, like add an "and" before the last element, this method falls short. You'd have to check each loop iteration for if it's on the last element. Adding a period, or newline after the list wouldn't be so bad, though. You could just add one more line after the for-loop to append whatever you desire to the list.
The second method I like a lot more. That one I'll call the print last method, as it does the same thing as the first but in reverse order.
Method 2: the print last method
if (!keywords.empty()) {
auto it = keywords.begin(), last = std::prev(keywords.end());
for (; it != last; it++) // Every preceding element.
out << *it << ", ";
out << "and " << *it << ".\n"; // Last element.
}
This one works by printing every element except for the last with a comma and space, allowing you to optionally add an "and" before it, a period after it, and/or a newline character. As you can see, this method gives you a lot more options on how you can handle that last element without affecting the performance of the loop or adding much code.
If it bothers you to leave the first part of the for-loop empty, you could write it like so:
if (!keywords.empty()) {
auto it, last;
for (it = keywords.begin(), last = std::prev(keywords.end()); it != last; it++)
out << *it << ", ";
out << "and " << *it << ".\n";
}
I would go with something like this, an easy solution and should work for all iterators.
int maxele = maxele = v.size() - 1;
for ( cur = v.begin() , i = 0; i < maxele ; ++i)
{
std::cout << *cur++ << " , ";
}
if ( maxele >= 0 )
{
std::cout << *cur << std::endl;
}
You can use a do loop, rewrite the loop condition for the first iteration, and use the short-circuit && operator and the fact that a valid stream is true.
auto iter = keywords.begin();
if ( ! keywords.empty() ) do {
out << * iter;
} while ( ++ iter != keywords.end() && out << ", " );
out << endl;
This one overloads the stream operator. Yes global variables are evil.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
int index = 0;
template<typename T, template <typename, typename> class Cont>
std::ostream& operator<<(std::ostream& os, const Cont<T, std::allocator<T>>& vec)
{
if (index < vec.size()) {
if (index + 1 < vec.size())
return os << vec[index++] << "-" << vec;
else
return os << vec[index++] << vec;
} else return os;
}
int main()
{
std::vector<int> nums(10);
int n{0};
std::generate(nums.begin(), nums.end(), [&]{ return n++; });
std::cout << nums << std::endl;
}
Can use functors:
#include <functional>
string getSeparatedValues(function<bool()> condition, function<string()> output, string separator)
{
string out;
out += output();
while (condition())
out += separator + output();
return out;
}
Example:
if (!keywords.empty())
{
auto iter = keywords.begin();
cout << getSeparatedValues([&]() { return ++iter != keywords.end(); }, [&]() { return *iter; }, ", ") << endl;
}
A combination of c++11 lambda and macro:
#define INFIX_PRINTER(os, sep)([&]()->decltype(os)&{static int f=1;os<<(f?(f=0,""):sep);return os;})()
Usage:
for(const auto& k: keywords)
INFIX_PRINTER(out, ", ") << k;
I like a range-based for with a is_last_elem test. That imho it's very readable:
for (auto& e : range)
{
if (!is_last_elem(e, range)) [[likely]]
os << e << ", ";
else
os << e;
}
os << std::endl;
Full code:
C++20:
#include <iostream>
#include <list>
#include <ranges>
#include <utility>
#include <type_traits>
#include <memory>
template <std::ranges::bidirectional_range R>
bool is_last_elem(const std::ranges::range_value_t<R>& elem, const R& range)
{
auto last_it = range.end();
std::advance(last_it, -1);
return std::addressof(elem) == std::addressof(*last_it);
}
template <std::ranges::bidirectional_range R, class Stream = std::ostream>
void print(const R& range, std::ostream& os = std::cout)
{
for (auto& e : range)
{
if (!is_last_elem(e, range)) [[likely]]
os << e << ", ";
else
os << e;
}
os << std::endl;
}
int main()
{
std::list<int> v{1, 2, 3, 4, 5};
print(v);
}
C++17:
#include <iostream>
#include <list>
#include <utility>
#include <type_traits>
#include <memory>
template <class Range>
using value_type_t = std::remove_reference_t<decltype(*std::begin(std::declval<Range>()))>;
template <class Range>
bool is_last_elem(const value_type_t<Range>& elem, const Range& range)
{
auto last_it = range.end();
std::advance(last_it, -1);
return std::addressof(elem) == std::addressof(*last_it);
}
template <class Range, class Stream = std::ostream>
void print(const Range& range, std::ostream& os = std::cout)
{
for (auto& e : range)
{
if (!is_last_elem(e, range))
os << e << ", ";
else
os << e;
}
os << std::endl;
}
int main()
{
std::list<int> v{1, 2, 3, 4, 5};
print(v);
}