How to change delimiter's position? - c++

This example :
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
int v[] = { 1, 2, 3 };
std::copy( &v[0], &v[3], std::ostream_iterator< int >( std::cout, "\n " ) );
}
produces next output :
1
2
3
Is there a way to change the example to make it produce next output?
1
2
3
PS I know I could use the for loop, but I am interested in a solution that uses algorithms and iterators.

There is no way to do this with std::ostream_iterator. (IMHO, there should
be, but it's not there.) If you don't mind writing an extra small
function or class,
you can use std::transform, e.g.:
struct FormatString
{
std::string operator()( std::string const& original ) const
{
return ' ' + original + '\n';
}
};
// ...
std::transform(
v.begin(), v.end(),
std::ostream_iterator<std::string>( std::cout ),
FormatString() );
If you have C++11, you can use a lambda for the FormatString.
I find the need for this occurs often enough that I've written a
PatsubstTransformer—a functional object which basically
implements the $(patsubst...) function of GNU make. So I would just
have to write:
std::transform(
v.begin(), v.end(),
std::ostream_iterator<std::string>( std::cout ),
PatsubstTransformer( "%", " %\n" ) );
I find I use this a lot. (I also find using std::transform more
appropriate than std::copy, since what I'm outputting is a
transformation.)

If you want to use C++11 you can use a lambda.
e.g like this:
int v[] = { 1, 2, 3};
std::for_each( &v[0], &v[3], [](int i){ std::cout << " " << i << "\n";} );

Use std::cout << " ", instead of std::cout as:
std::copy(v, v+3, std::ostream_iterator<int>(std::cout << " ", "\n " ) );
Here the expression std::cout << " " first evaluates which prints a single space to the output, and the evaluated value which is std::ostream& gets passed to std::ostream_iterator
Now the output will be aligned correctly:
1
2
3
Working code : http://www.ideone.com/kSdpk
By the way, don't write &v[3]. That invokes Undefined bevahior. Write v+3.

Output a single space before the std::copy.

No, not really. ostream_iterator isn't configurable like that.
So you'll have to use the pre-space "workaround" as found in other answers, and manually chop off that final line.
BTW It's been noted that &v[3], strictly speaking, invokes undefined behaviour due to the implicit dereference in the sub-expression v[3]. Prefer &v[0]+3 (or just v+3) — "having" a pointer to one-past-the-end of an array is okay, as long as it's not dereferenced.
You could make your own kind of ostream_iterator that does this, as the following example demonstrates.
Yes, it's verbose; however, you can also change it around however you like to suit your changing needs:
#include <iostream>
#include <iterator>
#include <algorithm>
template <class T, class charT = char, class traits = std::char_traits<charT> >
struct ostream_iterator_x
: std::iterator<std::output_iterator_tag, void, void, void, void> {
typedef charT char_type;
typedef traits traits_type;
typedef std::basic_ostream<charT,traits> ostream_type;
ostream_iterator_x(ostream_type& s, const charT* pre = 0, const charT* post = 0)
: s(s)
, pre(pre)
, post(post) {};
ostream_iterator_x(const ostream_iterator_x& x)
: s(x.s)
, pre(x.pre)
, post(x.post) {};
~ostream_iterator_x() {}
ostream_iterator_x& operator=(const T& value) {
if (pre != 0) s << pre;
s << value;
if (post != 0) s << post;
return *this;
}
ostream_iterator_x& operator*() { return *this; }
ostream_iterator_x& operator++() { return *this; }
ostream_iterator_x& operator++(int) { return *this; }
private:
ostream_type& s;
const charT* pre;
const charT* post;
};
int main()
{
int v[] = { 1, 2, 3 };
std::copy(v, v+3, ostream_iterator_x<int>(std::cout, " ", "\n"));
}
// Output:
// 1
// 2
// 3
(I used [n3290: 24.6/2] to determine the members and base-specification required for this to work and to be standard-compliant.)
Live demo.

Related

How to exit a function with a return value without using "return" in c++

How would I exit a function with a return value without using return.
Is there something like this in c++ :
auto random_function() {
printf("Random string"); // Gets executed
exit_with_return_value(/* Any random value. */);
printf("Same string as before"); // Doesn't get executed
}
Because I'm aware about exit() which takes a exit code.
But is there any way I could exit with a return value.
It is just that I can't call return is parentheses like this:
( return /* random value*/ );
But I can call functions in parentheses,
(exit(0));
My use case:
template <typename ...Parameters>
class Parameter_Pack
{
private:
void* paramsAddr[sizeof...(Parameters)];
public:
Parameter_Pack(Parameters ...parameters) {
size_t count = 0;
((
parameters,
this->paramsAddr[count] = malloc(sizeof(Parameters)),
*(Parameters*)paramsAddr[count] = parameters,
count++
), ...);
}
auto operator[](size_t index) {
size_t count = 0;
try {
(((count == index ? : return *
(Parameters*)paramsAddr[index] : *
(Parameters*)paramsAddr[index]), count++), ...);
} catch (Parameters...) {
std::cout << "Error: " << std::endl;
}
}
const size_t size() const {
return sizeof...(Parameters);
}
};
The problem is I can't return in auto operator[](size_t index).
The compiler error is :
"expected primary-expression before 'return'"
This doesn't answer your question directly, but instead of reinventing the wheel why not unpack the parameter pack into an std::tuple. You can then use std::get to access the object's by index.
#include <iostream>
#include <tuple>
template<typename ...Args>
static void unpack(Args&& ...args)
{
std::tuple pack{ std::forward<Args>(args)... };
int first = std::get<0>(pack);
std::cout << first << '\n';
const std::string& second = std::get<1>(pack);
std::cout << second << '\n';
bool third = std::get<2>(pack);
std::cout << std::boolalpha << third << '\n';
}
int main()
{
unpack(42, std::string{ "Some string" }, false);
}
OK, so the only thing I could come up with that kind of does what you want is to use a std::vector in conjunction with a std::variant.
Personally I think this would be an annoying API to use but it will allow you to return multiple types from the subscript operator and doesn't require a constant expression, i.e. index can be a runtime value.
#include <iostream>
#include <variant>
#include <vector>
#include <string>
template<typename ...Args>
class Pack {
public:
using Types = std::variant<Args...>;
Pack(Args... args)
: pack_{ std::move(args)... }
{}
Types& operator[](const std::size_t index) {
return pack_.at(index);
}
std::size_t size() const noexcept {
return pack_.size();
}
private:
std::vector<Types> pack_;
};
int main() {
Pack pack{42, std::string{ "Some string" }, false};
std::cout << pack.size() << '\n';
if (int* num = std::get_if<int>(&pack[0])) {
std::cout << "My num: " << *num << '\n';
}
}
return is a statement. Statements can't be part of a larger expression, so you can't return as a subexpression of some larger expression.
throw is an expression. It can be a subexpression of a larger expression, and you can throw any object you like.
It will be inconvenient for your callers, particularly if you mix it with an ordinary return. It will also not match the expectations other programmers have for how functions work. For that reason, I suggest you don't throw when you mean return.

Preserving insertion order on a std::set or std::unordered_set

Before marking this as duplicate, I have been here, here, and here, a duplicate of the first.
I'm aware of boost::multi_index, and use an environment where I lack it, and that a std::unordered_set is not bound to store elements in a deterministic insertion order.
I find the concept of using two containers, say an additional std::vector as uncouth.
What I would love is a solution involving a comparator that I can use in a std::set's template parameters (clarification, this could be a trivial functor struct, containing a bool operator()() overload, a regular function, or a lambda). Is it possible?
Addenda
Initialization must occur through a std:: container's begin iterator/end iterator constructor, such as in this snippet.
std::string str; cin >> str;
std::set<char>(str.begin(), str.end());
Also, another interesting use-case would be to create a dumb hash wrapping functor that allows insertion order to be pushed in to a std::unordered_set's template parameter.
You cannot directly have a lambda expression as the set's template parameter, because a lambda expression is a value, and the set's template parameter is a type. The obvious correction of the question, whether a construction using a lambda and decltype can work, leads to the interesting problem that a lambda expression denotes a unique type (a "closure type"), so you can never make two separate lambda expressions of the same closure type.*
However, in a more abstract sense what you want can be achieved in a local context using template argument deduction, for example:
template <typename F>
int f(int* first, int* last, F comp)
{
std::set<int, F> s(comp);
while (first != last) s.insert(*first++);
...
}
Now you can call f with a lambda expression as the argument, thus effectively "using a lambda as the set's comparator". Or, for a simpler example, you could just have a named variable for the lambda (putting all the template deduction into a single auto:
auto comp = [](...) { ... };
std::set<int, decltype(comp)> s(comp);
*) There is a proposal to allow lambdas in unevaluated contexts to address this point, but its outlook is uncertain. It has interesting side effects like making closure types affect name mangling.
An adt that preserves the order of insertion is an std::vector.
You can just as easily wrap it like this to get an std::set-like behavior:
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
template < typename T >
class VectorSet : public vector<T> {
public:
using iterator = typename vector<T>::iterator;
using value_type = typename vector<T>::value_type;
pair<iterator, bool> insert (const value_type& val) {
auto it = ::find(this->begin(), this->end(), val);
if (it == this->end())
it = ::vector<T>::insert(this->end(), val);
return pair<iterator, bool>(it, true);
}
};
int main()
{
VectorSet<int> my;
my.insert(1);
my.insert(4);
my.insert(3);
my.insert(4);
for (auto & v : my) {
cout << v << endl;
}
return 0;
}
You cannot, unless you use additional indexes. Two approaches:
1. using an explicit index
Live On Coliru
#include <set>
#include <vector>
#include <functional>
#include <algorithm>
using namespace std;
#include <iostream>
string read_word() {
string str;
cin >> str;
return str;
}
int main() {
using Ref = std::reference_wrapper<char const>;
auto const str = read_word();
std::cout << "Word: " << str << "\n";
auto v = [&]() -> vector<Ref> {
set<Ref> u(str.begin(), str.end());
return {u.begin(), u.end()};
}();
std::cout << "Unique: " << string(v.begin(), v.end()) << "\n";
auto pos = [str](char ch) { return str.find(ch); };
std::sort(v.begin(), v.end(), [pos](auto& a, auto& b) { return pos(a) < pos(b); });
std::cout << "Insertion: " << string(v.begin(), v.end()) << "\n";
}
Prints e.g.
Word: pineapple
Unique: aeilnp
Insertion: pineal
2. using Boost Multi-Index
Same deal
Live On Coliru
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
namespace bmi = boost::multi_index;
using Index = bmi::multi_index_container<char,
bmi::indexed_by<
bmi::sequenced<>,
bmi::ordered_unique<bmi::tag<struct unique>, bmi::identity<char> >
> > ;
#include <iostream>
std::string read_word() {
std::string str;
std::cin >> str;
return str;
}
int main() {
auto const str = read_word();
std::cout << "Word: " << str << "\n";
Index idx(str.begin(), str.end());
std::cout << "Insertion: " << std::string(idx.begin(), idx.end()) << "\n";
auto& u = idx.get<unique>();
std::cout << "Unique: " << std::string(u.begin(), u.end()) << "\n";
}
Prints
Word: pineapple
Insertion: pineal
Unique: aeilnp
I thought a weird solution (though not one involving any sets) could be to use a std::map of the element type and std::time_point as the key type. That will ensure insertion order if not anything at all.

C++: Printing or cout a standard library container to console

What's the C++ way to print or cout a C++ standard library container to the console, to view its contents?
On a separate note, why doesn't the C++ library actually overload the << operator for you? Any history behind it?
Overloading the operator<< for ostream is the way to go. Here's one possibility:
template <class container>
std::ostream& operator<<(std::ostream& os, const container& c)
{
std::copy(c.begin(),
c.end(),
std::ostream_iterator<typename container::value_type>(os, " "));
return os;
}
Then you can simply write:
std::cout << SomeContainer << std::endl;
Here are some other actually really nice solutions: Pretty-print C++ STL containers
The simplest way is to use the range-based for statement. For example
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
template <class Container>
std::ostream & display( const Container &container,
const char *s = " ",
std::ostream &os = std::cout )
{
for ( const auto &value : container )
{
os << value << s;
}
return os;
}
int main()
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::vector<int> v( std::begin( a ), std::end( a ) );
display( a, "; " );
std::cout << std::endl;
display( v );
std::cout << std::endl;
return 0;
}
The program output is
0; 1; 2; 3; 4; 5; 6; 7; 8; 9;
0 1 2 3 4 5 6 7 8 9
However a more flexibale approach will be to use standard algorithm std::copy. In this case you can set the displayed range yourself and use reverse iterators.
Also you can write the function such a way that it would get additional information.
why doesn't the C++ library actually overload the << operator for you?
Because any user can use his own approach to output a container as you can see from the output of my demonstrative program. In fact a container is a user-defined class and it is the user who should overload operator <<. There is exceptions for std::string and std::bitset but strings and bitsets are outputed as one entity without intermediate separates similarly to fundamental types.
For variety, make an adaptor, something like
template< typename T >
struct SequencePrinter
{
const T& t;
// ...
};
template< typename T >
SequencePrinter<T> sequence_printer(const T&);
template< typename T >
ostream& operator<<(ostream&, SequencePrinter<T>);
int main() {
vector<int> v;
// ...
cout << sequence_printer(v) << endl;
}
This allows the usual << notation, but doesn't try to force a particular choice of what << should mean with a sequence. It could, of course, be made fairly configurable too.

Viewing a raw pointer as a range in range-based for-loop

How can I make a raw pointer behave like a range, for a for-range loop syntax.
double five = 5;
double* dptr = &five;
for(int& d : dptr) std::cout << d << std::endl;// will not execute if the pointer is null
Motivation:
It is now vox populi that an boost::optional (future std::optional) value can be viewed as a range and therefore used in a for range loop http://faithandbrave.hateblo.jp/entry/2015/01/29/173613.
When I rewrote my own simplified version of it:
namespace boost {
template <class Optional>
decltype(auto) begin(Optional& opt) noexcept{
return opt?&*opt:nullptr;
}
template <class Optional>
decltype(auto) end(Optional& opt) noexcept{
return opt?std::next(&*opt):nullptr;
}
}
Used as
boost::optional<int> opt = 3;
for (int& x : opt) std::cout << x << std::endl;
While looking that code I imagined that it could be generalized to raw (nullable) pointers as well.
double five = 5;
double* dptr = &five;
for(int& d : dptr) std::cout << d << std::endl;
instead of the usual if(dptr) std::cout << *dptr << std::endl;. Which is fine but I wanted to achieve the other syntax above.
Attempts
First I tried to make the above Optional version of begin and end work for pointers but I couldn't. So I decided to be explicit in the types and remove all templates:
namespace std{ // excuse me, this for experimenting only, the namespace can be removed but the effect is the same.
double* begin(double* opt){
return opt?&*opt:nullptr;
}
double* end(double* opt){
return opt?std::next(&*opt):nullptr;
}
}
Almost there, it works for
for(double* ptr = std::begin(dptr); ptr != std::end(dptr); ++ptr)
std::cout << *ptr << std::endl;
But it doesn't work for the supposedly equivalent for-range loop:
for(double& d : dptr) std::cout << d << std::endl;
Two compilers tell me: error: invalid range expression of type 'double *'; no viable 'begin' function available
What is going on? Is there a compiler magic that forbids the ranged-loop to to work for pointers. Am I making a wrong assumption about the ranged-loop syntax?
Ironically, in the standard there is an overload for std::begin(T(&arr)[N]) and this is very close to it.
Note and a second though
Yes, the idea is silly because, even if possible this would be very confusing:
double* ptr = new double[10];
for(double& d : ptr){...}
would iterate over the first element only. A more clear and also realistic workaround would be to do something like workaround proposed by #Yakk:
for(double& d : boost::make_optional_ref(ptr)){...}
In this way it is clear that we are iterating over one element only and that that element is optional.
Ok, ok, I will go back to if(ptr) ... use *ptr.
Because the way that range-based for works is (from §6.5.4):
begin-expr and end-expr are determined as follows
— if _RangeT is an array type, [..]
— if _RangeT is a class type, [..]
— otherwise, begin-expr and end-expr are begin(__range) and end(__range), respectively, where begin
and end are looked up in the associated namespaces (3.4.2). [ Note: Ordinary unqualified lookup (3.4.1)
is not performed. —end note ]
What are the associated namespaces in this case? (§3.4.2/2, emphasis mine):
The sets of namespaces and classes are determined in the following way:
(2.1) — If T is a fundamental type, its associated sets of namespaces and classes are both empty.
Thus, there is no place to put your double* begin(double*) such that it will be called by the range-based for statement.
A workaround for what you want to do is just make a simple wrapper:
template <typename T>
struct PtrWrapper {
T* p;
T* begin() const { return p; }
T* end() const { return p ? p+1 : nullptr; }
};
for (double& d : PtrWrapper<double>{dptr}) { .. }
It is a useful lie to think that for(:) loops are implemented by "calling std::begin and std::end in a ADL-activated context". But that is a lie.
The standard instead basically does a parallel implementation of the std::begin and std::end in itself. This prevents the language's low level constructs from depending on its own library, which seems like a good idea.
The only lookup for begin by the language is the ADL-based lookup. Your pointer's std::begin won't be found, unless you are a pointer to something in std. The std::begin( T(&)[N} ) isn't found this way by the compiler, but instead that iteration is hard-coded by the language.
namespace boost {
template<class T>
T* begin( optional<T>&o ) {
return o?std::addressof(*o):nullptr;
}
template<class T>
T* begin( optional<T&>&&o ) {
return o?std::addressof(*o):nullptr;
}
template<class T>
T const* begin( optional<T> const&o ) {
return o?std::addressof(*o):nullptr;
}
template<class T>
T* end( optional<T>&o ) {
return o?std::next(begin(o)):nullptr;
}
template<class T>
T* end( optional<T&>&&o ) {
return o?std::next(begin(o)):nullptr;
}
template<class T>
T const* end( optional<T> const&o ) {
return o?std::next(begin(o)):nullptr;
}
template<class T>
boost::optional<T&> as_optional( T* t ) {
if (t) return *t;
return {};
}
}
now you can:
void foo(double * d) {
for(double& x : boost::as_optional(d)) {
std::cout << x << "\n";
}
without having to repeat the type double.
Note that an rvalue optional to a non-reference returns a T const*, while an rvalue optonal to a T& returns a T*. Iterating over a temporary in a writing context is probably an error.
TL;DR
This construct can be used in a range for loop:
std::views::counted(raw_ptr, !!raw_ptr)
Details
C++20 offers a plethora of ways to create ad-hoc iterables, using the ranges library. For example:
#include <ranges>
#include <iostream>
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *raw_ptr = a;
for(int i : std::views::counted(raw_ptr, 10))
std::cout << i << ' ';
std::cout << '\n';
for(int i : std::views::counted(raw_ptr, 1))
std::cout << i << ' ';
std::cout << '\n';
std::cout << "empty for null pointer pointer\n";
raw_ptr = nullptr;
for(int i : std::views::counted(raw_ptr, 0))
std::cout << i << ' ';
std::cout << '\n';
std::cout << "Exit\n";
}
Prints
1 2 3 4 5 6 7 8 9 10
1
empty for null pointer
Exit
Similarly std::views::subrange could be used with the (start, end] pointers. Check the library for more info.

member function alternative names

I am trying to create alternative names for the function call numberedFunction when it has certain values as below
template< typename T >
class X
{
public:
X() : single( std::bind( &X::numberedFunction, *this, 1 ) ),
halfDozen( std::bind( &X::numberedFunction, *this, 6 ) )
{ ... }
T numberedFunction( unsigned int i ) { ... }
const std::function< T() >& single;
const std::function< T() >& halfDozen;
};
But this code is not correct (segfaults when I try to use any of the specially named functions). Is there an issue with using this the way I am in the initialization list (e.g., is this not guarenteed to be well-formed at the time I am accessing it there)? Something else (obvious)? Is there a better way to do what I am trying to do (I feel like there almost definitely is)?
const std::function< T() >& single;
const std::function< T() >& halfDozen;
Your members are references to const, but you are initializing them from a temporary in the constructor (assuming the bind expressions in your real code aren't nonsensical). As soon as the construction is done they are invalid. Is this really what you intended?
Maybe this is what you want do do (using psychic powers here):
template< typename T >
class X
{
public:
X() : single( std::bind( &X::numberedFunction, this, 1 ) ),
halfDozen( std::bind( &X::numberedFunction, this, 6 ) )
{ ... }
T numberedFunction( unsigned int i ) { ... }
const std::function< T() > single;
const std::function< T() > halfDozen;
};
Notice that I'm binding to this, not *this. This avoids a copy, but may not be what you want.
An alternative approach is to just add a few forwarding functions:
T numberedFunction( unsigned int i ) { ... }
T single()
{ return numberedFunction(1); }
T halfDozen()
{ return numberedFunction(6); }
You're using this pointer in the initialization list. It's an uninitialized object. I wonder whether you could compile this code successfully or not!
See a sample to see the usage of bind (taken from MSDN)
// std_tr1__functional__bind.cpp
// compile with: /EHsc
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std::placeholders;
void square(double x)
{
std::cout << x << "^2 == " << x * x << std::endl;
}
void product(double x, double y)
{
std::cout << x << "*" << y << " == " << x * y << std::endl;
}
int main()
{
double arg[] = {1, 2, 3};
std::for_each(&arg[0], arg + 3, square);
std::cout << std::endl;
std::for_each(&arg[0], arg + 3, std::bind(product, _1, 2));
std::cout << std::endl;
std::for_each(&arg[0], arg + 3, std::bind(square, _1));
return (0);
}