www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - range.put() to Empty Array Causes Error?

reply Vijay Nayar <madric gmail.com> writes:
This code breaks with the following error:
void main()
{
	import std.range;
   	int[] vals = [];
	vals.put(3);
}
/src/phobos/std/range/primitives.d(2328): Attempting to fetch the 
front of an empty array of int

The following code has no error:
void main()
{
	import std.range;
   	int[] vals = [1];
	vals.put(3);
}

Why is range.put() not allowed for empty arrays?
Jun 17 2018
parent reply Steven Schveighoffer <schveiguy yahoo.com> writes:
On 6/17/18 7:07 AM, Vijay Nayar wrote:
 This code breaks with the following error:
 void main()
 {
      import std.range;
        int[] vals = [];
      vals.put(3);
 }
 /src/phobos/std/range/primitives.d(2328): Attempting to fetch the front 
 of an empty array of int
 
 The following code has no error:
 void main()
 {
      import std.range;
        int[] vals = [1];
      vals.put(3);
 }
 
 Why is range.put() not allowed for empty arrays?
 
 
range.put fills an existing array like a buffer, it does not append (as I'm guessing you are expecting). Use std.array.Appender to get append behavior. BTW, use put(vals, 3) instead of vals.put(3), as you may bypass the features of put. -Steve
Jun 17 2018
parent Seb <seb wilzba.ch> writes:
On Sunday, 17 June 2018 at 12:23:55 UTC, Steven Schveighoffer 
wrote:
 On 6/17/18 7:07 AM, Vijay Nayar wrote:
 This code breaks with the following error:
 void main()
 {
      import std.range;
        int[] vals = [];
      vals.put(3);
 }
 /src/phobos/std/range/primitives.d(2328): Attempting to fetch 
 the front of an empty array of int
 
 The following code has no error:
 void main()
 {
      import std.range;
        int[] vals = [1];
      vals.put(3);
 }
 
 Why is range.put() not allowed for empty arrays?
 
 
range.put fills an existing array like a buffer, it does not append (as I'm guessing you are expecting). Use std.array.Appender to get append behavior.
Or simply ~= if you want to use built-in arrays (works with Appender too FWIW).
Jun 17 2018