Is there a compact equivalent to Python range() in C++/STL - c++

How can I do the equivalent of the following using C++/STL? I want to fill a std::vector with a range of values [min, max).
# Python
>>> x = range(0, 10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I suppose I could use std::generate_n and provide a functor to generate the sequence, but I was wondering if there is a more succinct way of doing this using STL?

In C++11, there's std::iota:
#include <vector>
#include <numeric> //std::iota
int main() {
std::vector<int> x(10);
std::iota(std::begin(x), std::end(x), 0); //0 is the starting number
}
C++20 introduced a lazy version (just like Python) as part of the ranges library:
#include <iostream>
#include <ranges>
namespace views = std::views;
int main() {
for (int x : views::iota(0, 10)) {
std::cout << x << ' '; // 0 1 2 3 4 5 6 7 8 9
}
}

There is boost::irange:
std::vector<int> x;
boost::push_back(x, boost::irange(0, 10));

I ended up writing some utility functions to do this. You can use them as follows:
auto x = range(10); // [0, ..., 9]
auto y = range(2, 20); // [2, ..., 19]
auto z = range(10, 2, -2); // [10, 8, 6, 4]
The code:
#include <vector>
#include <stdexcept>
template <typename IntType>
std::vector<IntType> range(IntType start, IntType stop, IntType step)
{
if (step == IntType(0))
{
throw std::invalid_argument("step for range must be non-zero");
}
std::vector<IntType> result;
IntType i = start;
while ((step > 0) ? (i < stop) : (i > stop))
{
result.push_back(i);
i += step;
}
return result;
}
template <typename IntType>
std::vector<IntType> range(IntType start, IntType stop)
{
return range(start, stop, IntType(1));
}
template <typename IntType>
std::vector<IntType> range(IntType stop)
{
return range(IntType(0), stop, IntType(1));
}

I've been using this library for this exact purpose for years:
https://github.com/klmr/cpp11-range
Works very well and the proxies are optimized out.
for (auto i : range(1, 5))
cout << i << "\n";
for (auto u : range(0u))
if (u == 3u)
break;
else
cout << u << "\n";
for (auto c : range('a', 'd'))
cout << c << "\n";
for (auto i : range(100).step(-3))
if (i < 90)
break;
else
cout << i << "\n";
for (auto i : indices({"foo", "bar"}))
cout << i << '\n';

There is boost::irange, but it does not provide floating point, negative steps and can not directly initialize stl containers.
There is also numeric_range in my RO library
In RO, to initialize a vector:
vector<int> V=range(10);
Cut-n-paste example from doc page (scc - c++ snippet evaluator):
// [0,N) open-ended range. Only range from 1-arg range() is open-ended.
scc 'range(5)'
{0, 1, 2, 3, 4}
// [0,N] closed range
scc 'range(1,5)'
{1, 2, 3, 4, 5}
// floating point
scc 'range(1,5,0.5)'
{1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5}
// negative step
scc 'range(10,0,-1.5)'
{10, 8.5, 7, 5.5, 4, 2.5, 1}
// any arithmetic type
scc "range('a','z')"
a b c d e f g h i j k l m n o p q r s t u v w x y z
// no need for verbose iota. (vint - vector<int>)
scc 'vint V = range(5); V'
{0, 1, 2, 3, 4}
// is lazy
scc 'auto NR = range(1,999999999999999999l); *find(NR.begin(), NR.end(), 5)'
5
// Classic pipe. Alogorithms are from std::
scc 'vint{3,1,2,3} | sort | unique | reverse'
{3, 2, 1}
// Assign 42 to 2..5
scc 'vint V=range(0,9); range(V/2, V/5) = 42; V'
{0, 1, 42, 42, 42, 5, 6, 7, 8, 9}
// Find (brute force algorithm) maximum of `cos(x)` in interval: `8 < x < 9`:
scc 'range(8, 9, 0.01) * cos || max'
-0.1455
// Integrate sin(x) from 0 to pi
scc 'auto d=0.001; (range(0,pi,d) * sin || add) * d'
2
// Total length of strings in vector of strings
scc 'vstr V{"aaa", "bb", "cccc"}; V * size || add'
9
// Assign to c-string, then append `"XYZ"` and then remove `"bc"` substring :
scc 'char s[99]; range(s) = "abc"; (range(s) << "XYZ") - "bc"'
aXYZ
// Hide phone number:
scc "str S=\"John Q Public (650)1234567\"; S|isdigit='X'; S"
John Q Public (XXX)XXXXXXX

For those who can't use C++11 or libraries:
vector<int> x(10,0); // 0 is the starting number, 10 is the range size
transform(x.begin(),x.end(),++x.begin(),bind2nd(plus<int>(),1)); // 1 is the increment

A range() function similar to below will help:
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
// define range function (only once)
template <typename T>
vector <T> range(T N1, T N2) {
vector<T> numbers(N2-N1);
iota(numbers.begin(), numbers.end(), N1);
return numbers;
}
vector <int> arr = range(0, 10);
vector <int> arr2 = range(5, 8);
for (auto n : arr) { cout << n << " "; } cout << endl;
// output: 0 1 2 3 4 5 6 7 8 9
for (auto n : arr2) { cout << n << " "; } cout << endl;
// output: 5 6 7

I don't know of a way to do it like in python but another alternative is obviously to for loop through it:
for (int i = range1; i < range2; ++i) {
x.push_back(i);
}
chris's answer is better though if you have c++11

If you can't use C++11, you can use std::partial_sum to generate numbers from 1 to 10. And if you need numbers from 0 to 9, you can then subtract 1 using transform:
std::vector<int> my_data( 10, 1 );
std::partial_sum( my_data.begin(), my_data.end(), my_data.begin() );
std::transform(my_data.begin(), my_data.end(), my_data.begin(), bind2nd(std::minus<int>(), 1));

Some time ago I wrote the following _range class, which behaves like Python range (put it to the "range.h"):
#pragma once
#include <vector>
#include <cassert>
template < typename T = size_t >
class _range
{
const T kFrom, kEnd, kStep;
public:
///////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////
//
// INPUT:
// from - Starting number of the sequence.
// end - Generate numbers up to, but not including this number.
// step - Difference between each number in the sequence.
//
// REMARKS:
// Parameters must be all positive or all negative
//
_range( const T from, const T end, const T step = 1 )
: kFrom( from ), kEnd( end ), kStep( step )
{
assert( kStep != 0 );
assert( ( kFrom >= 0 && kEnd > 0 && kStep > 0 ) || ( kFrom < 0 && kEnd < 0 && kStep < 0 ) );
}
// Default from==0, step==1
_range( const T end )
: kFrom( 0 ), kEnd( end ), kStep( 1 )
{
assert( kEnd > 0 );
}
public:
class _range_iter
{
T fVal;
const T kStep;
public:
_range_iter( const T v, const T step ) : fVal( v ), kStep( step ) {}
operator T () const { return fVal; }
operator const T & () { return fVal; }
const T operator * () const { return fVal; }
const _range_iter & operator ++ () { fVal += kStep; return * this; }
bool operator == ( const _range_iter & ri ) const
{
return ! operator != ( ri );
}
bool operator != ( const _range_iter & ri ) const
{
// This is a tricky part - when working with iterators
// it checks only once for != which must be a hit to stop;
// However, this does not work if increasing kStart by N times kSteps skips over kEnd
return fVal < 0 ? fVal > ri.fVal : fVal < ri.fVal;
}
};
const _range_iter begin() { return _range_iter( kFrom, kStep ); }
const _range_iter end() { return _range_iter( kEnd, kStep ); }
public:
// Conversion to any vector< T >
operator std::vector< T > ( void )
{
std::vector< T > retRange;
for( T i = kFrom; i < kEnd; i += kStep )
retRange.push_back( i );
return retRange; // use move semantics here
}
};
// A helper to use pure range meaning _range< size_t >
typedef _range<> range;
And some test code looks like the following one:
#include "range.h"
#include <iterator>
#include <fstream>
using namespace std;
void RangeTest( void )
{
ofstream ostr( "RangeTest.txt" );
if( ostr.is_open() == false )
return;
// 1:
ostr << "1st test:" << endl;
vector< float > v = _range< float >( 256 );
copy( v.begin(), v.end(), ostream_iterator< float >( ostr, ", " ) );
// 2:
ostr << endl << "2nd test:" << endl;
vector< size_t > v_size_t( range( 0, 100, 13 ) );
for( auto a : v_size_t )
ostr << a << ", ";
// 3:
ostr << endl << "3rd test:" << endl;
auto vvv = range( 123 ); // 0..122 inclusive, with step 1
for( auto a : vvv )
ostr << a << ", ";
// 4:
ostr << endl << "4th test:" << endl;
// Can be used in the nested loops as well
for( auto i : _range< float >( 0, 256, 16.5 ) )
{
for( auto j : _range< int >( -2, -16, -3 ) )
{
ostr << j << ", ";
}
ostr << endl << i << endl;
}
}

As an iterator:
#include <iostream>
class Range {
int x, y, z;
public:
Range(int x) {this->x = 0; this->y = x; this->z = 1;}
Range(int x, int y) {this->x = x; this->y = y; this->z = 1;}
Range(int x, int y, int z) {this->x = x; this->y = y; this->z = z;}
struct Iterator
{
Iterator (int val, int inc) : val{val}, inc{inc} {}
Iterator& operator++(){val+=inc; return *this;}
int operator*() const {return val;}
friend bool operator!=(const Iterator& a, const Iterator& b){return a.val < b.val;}
private:
int val, inc;
};
Iterator begin() {return Iterator(x,z);}
Iterator end() {return Iterator(y,z);}
};
int main() {
for (auto i: Range(10))
{
std::cout << i << ' '; //0 1 2 3 4 5 6 7 8 9
}
std::cout << '\n';
for (auto i: Range(1,10))
{
std::cout << i << ' '; //1 2 3 4 5 6 7 8 9
}
std::cout << '\n';
for (auto i: Range(-10,10,3))
{
std::cout << i << ' '; //-10 -7 -4 -1 2 5 8
}
return 0;
}

Related

Maximum product C++

I am given a few array of both negative and positive numbers.
I should Find the maximum product obtained from multiplying 2 adjacent numbers in the array.
This is the code I wrote :
#include <vector>
#include <iostream>
using namespace std;
int adjacentElementsProduct(vector<int> inputArray)
{
for(int i = 0; i < inputArray.size(); i++) {
if((inputArray[i] * inputArray[i+1])>(inputArray[i+1] * inputArray[i+2])) {
std::cout << inputArray[i] * inputArray[i+1] << "\n";
} else if((inputArray[i+1] * inputArray[i+2])>(inputArray[i+2] * inputArray[i+3])) {
std::cout << inputArray[i+1] * inputArray[i+2] << "\n";
} else if((inputArray[i+2] * inputArray[i+3])>(inputArray[i+3] * inputArray[i+4])) {
std::cout << inputArray[i+2] * inputArray[i+3] << "\n";
} else if((inputArray[i+3] * inputArray[i+4])>(inputArray[i+4] * inputArray[i+5])) {
std::cout << inputArray[i+3] * inputArray[i+4] << "\n";
} else {
std::cout << "Unknow" << "\n";
} return 1;
}
}
int main() {
adjacentElementsProduct({5, 8});
adjacentElementsProduct({1,2,3});
adjacentElementsProduct({1,5,10,9});
adjacentElementsProduct({5,1,2,3,1,4});
adjacentElementsProduct({4,12,3,1,5});
adjacentElementsProduct({3,6,-2,-5,7,3});
adjacentElementsProduct({9, 5, 10, 2, 24, -1, -48});
adjacentElementsProduct({5, 6, -4, 2, 3, 2, -23});
adjacentElementsProduct({-23, 4, -5, 99, -27, 329, -2, 7, -921});
adjacentElementsProduct({1,0,1,0,1000});
adjacentElementsProduct({1,2,3,0});
return 1 ;
}
Output:
40
6
90
5
48
18
50
30
-20
Unknow
6
The code only compares the product of inputArray[i] * inputArray[i+1] and inputArray[i+1] * inputArray[i+2] But I want to find the maximum product among all the numbers in array.
You want to loop over the input vector and compute the products of adjacent elements.
Then, you want to find the maximum of those products. You don't need all that hardcoded [i+1], [i+2], [i+3], ... shenanigans, you already have something that can get all those numbers for you -- a for loop.
int adjacentElementsProduct(vector<int> inputArray)
{
// Set initial max product to a very small number so that
// it is always replaced by our first product
int maxProduct = std::numeric_limits<int>::min();
for(int i = 0;
i < inputArray.size() - 1; /* because we will be doing i + 1 inside the loop */
i++) {
// Calculate product of this and next element
int product = inputArray[i] * inputArray[i + 1];
if (product > maxProduct)
maxProduct = product; // This product is the greatest so far,
// so keep it and get rid of the old max.
}
return maxProduct;
}
To explain how this works, let's look at the execution of the function for an example input. Let's say we do adjacentElementsProduct({5,1,2,3,1,4});
maxProduct is set to some very large negative number (let's say -99999999)
inputArray.size() is 6. inputArray.size() - 1 is 5.
i = 0. Is 0 < 5? Yes. Go inside loop
product = inputArray[0] * inputArray[1] = 5
is 5 > maxProduct (-99999999)? Yes. Set maxProduct = 5
Increment i to 1.
i = 1. Is 1 < 5? Yes. Go inside loop
product = inputArray[1] * inputArray[2] = 2
is 2 > maxProduct (5)? No.
Increment i to 2.
i = 2. Is 2 < 5? Yes. Go inside loop
product = inputArray[2] * inputArray[3] = 6
is 6 > maxProduct (5)? Yes. Set maxProduct = 6
Increment i to 3.
i = 3. Is 3 < 5? Yes. Go inside loop
product = inputArray[3] * inputArray[4] = 3
is 3 > maxProduct (6)? No.
Increment i to 4.
i = 4. Is 4 < 5? Yes. Go inside loop
product = inputArray[4] * inputArray[5] = 4
is 4 > maxProduct (6)? No.
Increment i to 5.
i = 5. Is 5 < 5? No.
Return maxProduct, which is 6.
I think your function is overkill. You can do this with a running maxima:
const unsigned int length = inputArray.length();
int maximum = inputArray[0] * inputArray[1];
for (unsigned int i = 1U; i < (length - 1U); ++i)
{
const int product = inputArray[i] * inputArray[i + 1];
if (product > maximum) maximum = product;
}
This can be further optimized but that is an exercise for the OP.
Edit 1: Via Pointers
This may be more optimal, but only assembly language will tell (or profiling):
const unsigned int length = inputArray.length();
int const * p_first = &inputArray[0];
int const * p_second = &inputArray[1];
int maximum = (*p_first++) * (*p_second++);
for (unsigned int i = 1u; i < (length - 1); ++i)
{
int product = (*p_first++) * (*p_second++);
if (product > maximum) maximum = product;
}
In the above code fragment, the two array locations are maintained in pointers. The pointers can be maintained in registers. No need to calculate the offset within the loop each time. Incrementing pointers is simple and quick operation. Some processors have instructions that can dereference a pointer and increment in a single instruction. Some compilers may perform this optimization depending on the optimization setting.
Edit 2: Tracking Previous Value
Another optimization is to reduce the memory accesses by about half, by remembering the previous value in the array:
const unsigned int length = inputArray.length();
int previous = inputArray[0];
int next = inputArray[1];
int maximum = previous * next;
previous = next;
for (unsigned int i = 1u; i < length; ++i)
{
next = inputArray[i];
const int product = previous * next;
if (product > maximum) maximum = product;
previous = next;
}
In the above code fragment, the previous array value is remembered in a variable. This eliminates the need to access the array for the previous value; only one array access is required.
The compiler may perform this optimization at higher optimization levels. The proof is to compare the assembly language of the variables fragments.
There's an algorithm in <numeric> that does this for you:
int adjacentElementsProduct(std::vector<int> const & inputArray)
{
// [[assert: inputArray.size > 1 ]]
return std::inner_product(inputArray.begin(), inputArray.end() - 1,
inputArray.begin() + 1,
0,
[](int i, int j) { return std::max(i, j); },
std::multiplies{});
}
which is about as efficient, and readable as it gets.
For starters the function should not output any message. It is the caller of the function will decide whether to output a message or not.
The function should return an iterator or a pair of iterators that point to the two adjacent elements with the maximum product.
As for your function implementation then it has undefined behavior because it can access non-existent elements of the vector.
I can suggest the following function definition as it is shown in the demonstrative program below.
#include <iostream>
#include <utility>
#include <vector>
#include <iterator>
std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator>
adjacentElementsProduct( const std::vector<int> &v )
{
std::pair<std::vector<int>::const_iterator, std::vector<int>::const_iterator>
p = { std::begin( v ), std::end( v ) };
if (not ( v.size() < 2 ))
{
p.second = std::next( std::begin( v ) );
long long int max_product = static_cast<long long int>( *p.first ) * *p.second;
for (auto prev = p.second, current = std::next( p.second );
current != std::end( v );
std::advance( prev, 1 ), std::advance( current, 1 ))
{
if (max_product < static_cast<long long int>( *prev ) * *current)
{
p = { prev, current };
}
}
}
return p;
}
int main()
{
std::vector<int> v = { 5, 8 };
auto p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( *p.first ) * *p.second << '\n';
v = { 1,2,3 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( *p.first ) * *p.second << '\n';
v = { 1,5,10,9 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( *p.first ) * *p.second << '\n';
v = { 5,1,2,3,1,4 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( *p.first ) * *p.second << '\n';
v = { 4,12,3,1,5 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( *p.first ) * *p.second << '\n';
v = { 3,6,-2,-5,7,3 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( *p.first ) * *p.second << '\n';
v = { 9, 5, 10, 2, 24, -1, -48 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( *p.first ) * *p.second << '\n';
v = { 5, 6, -4, 2, 3, 2, -23 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( *p.first ) * *p.second << '\n';
v = { -23, 4, -5, 99, -27, 329, -2, 7, -921 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( *p.first ) * *p.second << '\n';
v = { 1, 0, 1, 0, 1000 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( *p.first ) * *p.second << '\n';
v = { 1,2,3,0 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( *p.first ) * *p.second << '\n';
}
The program output is
40
6
90
6
48
21
48
30
-14
0
6
If you do not know yet iterators than the function can be defined the following way
#include <iostream>
#include <utility>
#include <vector>
std::pair<std::vector<int>::size_type, std::vector<int>::size_type>
adjacentElementsProduct( const std::vector<int> &v )
{
std::pair<std::vector<int>::size_type, std::vector<int>::size_type>
p = { 0, v.size() };
if (not ( v.size() < 2 ))
{
p.second = 1;
long long int max_product = static_cast<long long int>( p.first ) * p.second;
for (std::vector<int>::size_type i = 3; i < v.size(); i++ )
{
if (max_product < static_cast<long long int>( v[i - 1] ) * v[i] )
{
p = { i - 1, i };
}
}
}
return p;
}
int main()
{
std::vector<int> v = { 5, 8 };
auto p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( p.first ) * p.second << '\n';
v = { 1,2,3 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( p.first ) * p.second << '\n';
v = { 1,5,10,9 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( p.first ) * p.second << '\n';
v = { 5,1,2,3,1,4 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( p.first ) * p.second << '\n';
v = { 4,12,3,1,5 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( p.first ) * p.second << '\n';
v = { 3,6,-2,-5,7,3 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( p.first ) * p.second << '\n';
v = { 9, 5, 10, 2, 24, -1, -48 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( p.first ) * p.second << '\n';
v = { 5, 6, -4, 2, 3, 2, -23 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( p.first ) * p.second << '\n';
v = { -23, 4, -5, 99, -27, 329, -2, 7, -921 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( p.first ) * p.second << '\n';
v = { 1, 0, 1, 0, 1000 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( p.first ) * p.second << '\n';
v = { 1,2,3,0 };
p = adjacentElementsProduct( v );
std::cout << static_cast< long long int >( p.first ) * p.second << '\n';
}

What algorithm can I use in this liner function question?

Firstly, I would like to apologise for my bad English.
when I submit the code below to DomJudge I got TimeLimit ERROR.
I can't think of ways to solve this question albeit I searched all over the internet and still couldn't find a solution.
Can someone give me a hint?
Question:
Here are N linear function fi(x) = aix + bi, where 1 ≤ i ≤ N。Define F(x) = maxifi(x). Please compute
the following equation for the input c[i], where 1 ≤ i ≤ m.
**Σ(i=1 to m) F(c[i])**
For example, given 4 linear function as follows. f1(x) = –x, f2 = x, f3 = –2x – 3, f4 = 2x – 3. And the
input is c[1] = 4, c[2] = –5, c[3] = –1, c[4] = 0, c[5] = 2. We have F(c[1]) = 5, F(c[2]) = 7, F(c[3])
= 1, F(c[4]) = 0, F(c[5]) = 2. Then,
**Σ(i=1 to 5)𝐹(𝑐[𝑖])
= 𝐹(𝑐[1]) + 𝐹(𝑐[2]) + 𝐹(𝑐[3]) + 𝐹(𝑐[4]) + 𝐹([5]) = 5 + 7 + 1 + 0 + 2 = 15**
Input Format:
The first line contains two positive integers N and m. The next N lines will contain two integers ai
and bi, and the last line will contain m integers c[1], c[2], c[3],…, c[m]. Each element separated by
a space.
Output Format:
Please output the value of the above function.
question image:https://i.stack.imgur.com/6HeaA.png
Sample Input:
4 5
-1 0
1 0
-2 -3
2 -3
4 -5 -1 0 2
Sample Output:
15
My Program
#include <iostream>
#include <vector>
struct L
{
int a;
int b;
};
int main()
{
int n{ 0 };
int m{ 0 };
while (std::cin >> n >> m)
{
//input
std::vector<L> arrL(n);
for (int iii{ 0 }; iii < n; ++iii)
{
std::cin >> arrL[iii].a >> arrL[iii].b;
}
//find max in every linear polymore
int answer{ 0 };
for (int iii{ 0 }; iii < m; ++iii)
{
int input{ 0 };
int max{ 0 };
std::cin >> input;
max = arrL[0].a * input + arrL[0].b;
for (int jjj{ 1 }; jjj < n; ++jjj)
{
int tmp{arrL[jjj].a * input + arrL[jjj].b };
if (tmp > max)max = tmp;
}
answer += max;
}
//output
std::cout << answer << '\n';
}
return 0;
}
Your solution is O(n*m).
A faster solution is obtained by iteratively determinating the "dominating segments", and the correspong crossing points, called "anchors" in the following.
Each anchor is linked to two segments, on its left and on its right.
The first step consists in sorting the lines according to the a values, and then adding each new line iteratively.
When adding line i, we know that this line is dominant for large input values, and must be added (even if it will be removed in the following steps).
We calculate the intersection of this line with the previous added line:
if the intersection value is higher than the rightmost anchor, then we add a new anchor corresponding to this new line
if the intersection value is lower than the rightmost anchor, then we know that we have to suppress this last anchor value. In this case, we iterate the process, calculating now the intersection with the right segment of the previous anchor.
Complexity is dominated by sorting: O(nlogn + mlogm). The anchor determination process is O(n).
When we have the anchors, then determining the rigtht segment for each input x value is O(n+ m). If needed, this last value could be further reduced with a binary search (not implemented).
Compared to first version of the code, a few errors have been corrected. These errors were concerning some corner cases, with some identical lines at the extreme left (i.e. lowest values of a). Besides, random sequences have been generated (more than 10^7), for comparaison of the results with those obtained by OP's code. No differences were found. It is likely that if some errors remain, they correspond to other unknown corner cases. The algorithm by itself looks quite valid.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
// lines of equation `y = ax + b`
struct line {
int a;
int b;
friend std::ostream& operator << (std::ostream& os, const line& coef) {
os << "(" << coef.a << ", " << coef.b << ")";
return os;
}
};
struct anchor {
double x;
int segment_left;
int segment_right;
friend std::ostream& operator << (std::ostream& os, const anchor& anc) {
os << "(" << anc.x << ", " << anc.segment_left << ", " << anc.segment_right << ")";
return os;
}
};
// intersection of two lines
double intersect (line& seg1, line& seg2) {
double x;
x = double (seg1.b - seg2.b) / (seg2.a - seg1.a);
return x;
}
long long int max_funct (std::vector<line>& lines, std::vector<int> absc) {
long long int sum = 0;
auto comp = [&] (line& x, line& y) {
if (x.a == y.a) return x.b < y.b;
return x.a < y.a;
};
std::sort (lines.begin(), lines.end(), comp);
std::sort (absc.begin(), absc.end());
// anchors and dominating segments determination
int n = lines.size();
std::vector<anchor> anchors (n+1);
int n_anchor = 1;
int l0 = 0;
while ((l0 < n-1) && (lines[l0].a == lines[l0+1].a)) l0++;
int l1 = l0 + 1;
if (l0 == n-1) {
anchors[0] = {0.0, l0, l0};
} else {
while ((l1 < n-1) && (lines[l1].a == lines[l1+1].a)) l1++;
double x = intersect(lines[l0], lines[l1]);
anchors[0] = {x, l0, l1};
for (int i = l1 + 1; i < n; ++i) {
if ((i != (n-1)) && lines[i].a == lines[i+1].a) continue;
double x = intersect(lines[anchors[n_anchor-1].segment_right], lines[i]);
if (x > anchors[n_anchor-1].x) {
anchors[n_anchor].x = x;
anchors[n_anchor].segment_left = anchors[n_anchor - 1].segment_right;
anchors[n_anchor].segment_right = i;
n_anchor++;
} else {
n_anchor--;
if (n_anchor == 0) {
x = intersect(lines[anchors[0].segment_left], lines[i]);
anchors[0] = {x, anchors[0].segment_left, i};
n_anchor = 1;
} else {
i--;
}
}
}
}
// sum calculation
int j = 0; // segment index (always increasing)
for (int x: absc) {
while (j < n_anchor && anchors[j].x < x) j++;
line seg;
if (j == 0) {
seg = lines[anchors[0].segment_left];
} else {
if (j == n_anchor) {
if (anchors[n_anchor-1].x < x) {
seg = lines[anchors[n_anchor-1].segment_right];
} else {
seg = lines[anchors[n_anchor-1].segment_left];
}
} else {
seg = lines[anchors[j-1].segment_right];
}
}
sum += seg.a * x + seg.b;
}
return sum;
}
int main() {
std::vector<line> lines = {{-1, 0}, {1, 0}, {-2, -3}, {2, -3}};
std::vector<int> x = {4, -5, -1, 0, 2};
long long int sum = max_funct (lines, x);
std::cout << "sum = " << sum << "\n";
lines = {{1,0}, {2, -12}, {3, 1}};
x = {-3, -1, 1, 5};
sum = max_funct (lines, x);
std::cout << "sum = " << sum << "\n";
}
One possible issue is the loss of information when calculating the double x corresponding to line intersections, and therefoe to anchors. Here is a version using Rational to avoid such loss.
#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
struct Rational {
int p, q;
Rational () {p = 0; q = 1;}
Rational (int x, int y) {
p = x;
q = y;
if (q < 0) {
q -= q;
p -= p;
}
}
Rational (int x) {
p = x;
q = 1;
}
friend std::ostream& operator << (std::ostream& os, const Rational& x) {
os << x.p << "/" << x.q;
return os;
}
friend bool operator< (const Rational& x1, const Rational& x2) {return x1.p*x2.q < x1.q*x2.p;}
friend bool operator> (const Rational& x1, const Rational& x2) {return x2 < x1;}
friend bool operator<= (const Rational& x1, const Rational& x2) {return !(x1 > x2);}
friend bool operator>= (const Rational& x1, const Rational& x2) {return !(x1 < x2);}
friend bool operator== (const Rational& x1, const Rational& x2) {return x1.p*x2.q == x1.q*x2.p;}
friend bool operator!= (const Rational& x1, const Rational& x2) {return !(x1 == x2);}
};
// lines of equation `y = ax + b`
struct line {
int a;
int b;
friend std::ostream& operator << (std::ostream& os, const line& coef) {
os << "(" << coef.a << ", " << coef.b << ")";
return os;
}
};
struct anchor {
Rational x;
int segment_left;
int segment_right;
friend std::ostream& operator << (std::ostream& os, const anchor& anc) {
os << "(" << anc.x << ", " << anc.segment_left << ", " << anc.segment_right << ")";
return os;
}
};
// intersection of two lines
Rational intersect (line& seg1, line& seg2) {
assert (seg2.a != seg1.a);
Rational x = {seg1.b - seg2.b, seg2.a - seg1.a};
return x;
}
long long int max_funct (std::vector<line>& lines, std::vector<int> absc) {
long long int sum = 0;
auto comp = [&] (line& x, line& y) {
if (x.a == y.a) return x.b < y.b;
return x.a < y.a;
};
std::sort (lines.begin(), lines.end(), comp);
std::sort (absc.begin(), absc.end());
// anchors and dominating segments determination
int n = lines.size();
std::vector<anchor> anchors (n+1);
int n_anchor = 1;
int l0 = 0;
while ((l0 < n-1) && (lines[l0].a == lines[l0+1].a)) l0++;
int l1 = l0 + 1;
if (l0 == n-1) {
anchors[0] = {0.0, l0, l0};
} else {
while ((l1 < n-1) && (lines[l1].a == lines[l1+1].a)) l1++;
Rational x = intersect(lines[l0], lines[l1]);
anchors[0] = {x, l0, l1};
for (int i = l1 + 1; i < n; ++i) {
if ((i != (n-1)) && lines[i].a == lines[i+1].a) continue;
Rational x = intersect(lines[anchors[n_anchor-1].segment_right], lines[i]);
if (x > anchors[n_anchor-1].x) {
anchors[n_anchor].x = x;
anchors[n_anchor].segment_left = anchors[n_anchor - 1].segment_right;
anchors[n_anchor].segment_right = i;
n_anchor++;
} else {
n_anchor--;
if (n_anchor == 0) {
x = intersect(lines[anchors[0].segment_left], lines[i]);
anchors[0] = {x, anchors[0].segment_left, i};
n_anchor = 1;
} else {
i--;
}
}
}
}
// sum calculation
int j = 0; // segment index (always increasing)
for (int x: absc) {
while (j < n_anchor && anchors[j].x < x) j++;
line seg;
if (j == 0) {
seg = lines[anchors[0].segment_left];
} else {
if (j == n_anchor) {
if (anchors[n_anchor-1].x < x) {
seg = lines[anchors[n_anchor-1].segment_right];
} else {
seg = lines[anchors[n_anchor-1].segment_left];
}
} else {
seg = lines[anchors[j-1].segment_right];
}
}
sum += seg.a * x + seg.b;
}
return sum;
}
long long int max_funct_op (const std::vector<line> &arrL, const std::vector<int> &x) {
long long int answer = 0;
int n = arrL.size();
int m = x.size();
for (int i = 0; i < m; ++i) {
int input = x[i];
int vmax = arrL[0].a * input + arrL[0].b;
for (int jjj = 1; jjj < n; ++jjj) {
int tmp = arrL[jjj].a * input + arrL[jjj].b;
if (tmp > vmax) vmax = tmp;
}
answer += vmax;
}
return answer;
}
int main() {
long long int sum, sum_op;
std::vector<line> lines = {{-1, 0}, {1, 0}, {-2, -3}, {2, -3}};
std::vector<int> x = {4, -5, -1, 0, 2};
sum_op = max_funct_op (lines, x);
sum = max_funct (lines, x);
std::cout << "sum = " << sum << " sum_op = " << sum_op << "\n";
}
To reduce the time complexity from O(n*m) to something near O(nlogn), we need to order the input data in some way.
The m points where the target function is sampled can be easily sorted using std::sort, which has an O(mlogm) complexity in terms of comparisons.
Then, instead of searching the max between all the lines for each point, we can take advantage of a divide-and-conquer technique.
Some considerations can be made in order to create such an algorithm.
If there are no lines or no sample points, the answer is 0.
If there is only one line, we can evaluate it at each point, accumulating the values and return the result. In case of two lines we could easily accumulate the max between two values. Searching for the intersection and then separating the intervals to accumulate only the correct value may be more complicated, with multiple corner cases and overflow issues.
A recursive function accepting a list of lines, points and two special lines left and right, may start by calculating the middle point in the set of points. Then it could find the two lines (or the only one) that have the greater value at that point. One of them also have the greatest slope between all the ones passing for that maximum point, that would be the top "right". The other one, the top "left" (which may be the same one), have the least slope.
We can partition all the remaining lines in three sets.
All the lines having a greater slope than the "top right" one (but lower intercept). Those are the ones that we need to evaluate the sum for the subset of points at the right of the middle point.
All the lines having a lower slope than the "top left" one (but lower intercept). Those are the ones that we need to evaluate the sum for the subset of points at the left of the middle point.
The remaining lines, that won't partecipate anymore and can be removed. Note this includes both "top right" and "top left".
Having splitted both the points and the lines, we can recurively call the same function passing those subsets, along with the previous left line and "top left" as left and right to the left, and the "top right" line with the previous right as left and right to the right.
The return value of this function is the sum of the value at the middle point plus the return values of the two recursive calls.
To start the procedure, we don't need to evaluate the correct left and right at the extreme points, we can use an helper function as entry point which sorts the points and calls the recursive function passing all the lines, the points and two dummy values (the lowest possible line, y = 0 + std::numeric_limits<T>::min()).
The following is a possible implementation:
#include <algorithm>
#include <iostream>
#include <vector>
#include <numeric>
#include <limits>
struct Line
{
using value_type = long;
using result_type = long long;
value_type slope;
value_type intercept;
auto operator() (value_type x) const noexcept {
return static_cast<result_type>(x) * slope + intercept;
}
static constexpr Line min() noexcept {
return { 0, std::numeric_limits<value_type>::min()};
}
};
auto result_less_at(Line::value_type x)
{
return [x] (Line const& a, Line const& b) { return a(x) < b(x); };
}
auto slope_less_than(Line::value_type slope)
{
return [slope] (Line const& line) { return line.slope < slope; };
}
auto slope_greater_than(Line::value_type slope)
{
return [slope] (Line const& line) { return slope < line.slope; };
}
auto accumulate_results(Line const& line)
{
return [line] (Line::result_type acc, Line::value_type x) {
return acc + line(x);
};
}
struct find_max_lines_result_t
{
Line::result_type y_max;
Line left, right;
};
template< class LineIt, class XType >
auto find_max_lines( LineIt first_line, LineIt last_line
, Line left, Line right
, XType x )
{
auto result{ [left, right] (const auto max_left, const auto max_right)
-> find_max_lines_result_t {
if ( max_left < max_right )
return { max_right, right, right };
else if ( max_right < max_left )
return { max_left, left, left };
else
return { max_left, left, right };
}(left(x), right(x))
};
std::for_each( first_line, last_line
, [x, &result] (Line const& line) mutable {
auto const y{ line(x) };
if ( y == result.y_max ) {
if ( result.right.slope < line.slope )
result.right = line;
if ( line.slope < result.left.slope )
result.left = line;
}
else if ( result.y_max < y ) {
result = {y, line, line};
}
} );
return result;
}
template< class SampleIt >
auto sum_left_right_values( SampleIt const first_x, SampleIt const last_x
, Line const left, Line const right )
{
return std::accumulate( first_x, last_x, Line::result_type{},
[left, right] (Line::result_type acc, Line::value_type x) {
return acc + std::max(left(x), right(x)); } );
}
template< class LineIt, class XType >
auto find_max_result( LineIt const first_line, LineIt const last_line
, Line const left, Line const right
, XType const x )
{
auto const y_max{ std::max(left(x), right(x)) };
LineIt const max_line{ std::max_element(first_line, last_line, result_less_at(x)) };
return max_line == last_line ? y_max : std::max(y_max, (*max_line)(x));
}
template <class LineIt, class SampleIt>
auto sum_lines_max_impl( LineIt const first_line, LineIt const last_line,
SampleIt const first_x, SampleIt const last_x,
Line const left, Line const right )
{
if ( first_x == last_x ) {
return Line::result_type{};
}
if ( first_x + 1 == last_x ) {
return find_max_result(first_line, last_line, left, right, *first_x);
}
if ( first_line == last_line ) {
return sum_left_right_values(first_x, last_x, left, right);
}
auto const mid_x{ first_x + (last_x - first_x - 1) / 2 };
auto const top{ find_max_lines(first_line, last_line, left, right, *mid_x) };
auto const right_begin{ std::partition( first_line, last_line
, slope_less_than(top.left.slope) ) };
auto const right_end{ std::partition( right_begin, last_line
, slope_greater_than(top.right.slope) ) };
return top.y_max + sum_lines_max_impl( first_line, right_begin
, first_x, mid_x
, left, top.left )
+ sum_lines_max_impl( right_begin, right_end
, mid_x + 1, last_x
, top.right, right );
}
template <class LineIt, class SampleIt>
auto sum_lines_max( LineIt first_line, LineIt last_line
, SampleIt first_sample, SampleIt last_sample )
{
if ( first_line == last_line )
return Line::result_type{};
std::sort(first_sample, last_sample);
return sum_lines_max_impl( first_line, last_line
, first_sample, last_sample
, Line::min(), Line::min() );
}
int main()
{
std::vector<Line> lines{ {-1, 0}, {1, 0}, {-2, -3}, {2, -3} };
std::vector<long> points{ 4, -5, -1, 0, 2 };
std::cout << sum_lines_max( lines.begin(), lines.end()
, points.begin(), points.end() ) << '\n';
}
Testable here.

Custom comparator for std::map not working

I experienced the following phenomenon when writing some C++ code:
I have a map looking like this:
std::map<test_struct_t*, unsigned int, cmp_by_value> testmap;
This map lies globally in my program and the struct is defined as:
struct test_struct_t {
int x; int y; int val;
bool operator<(const test_struct_t &o) const {
return x < o.x || y < o.y || val < o.val;
}
test_struct_t(int a, int b, int c) : x(a), y(b), val(c) {}
};
The custom comparator I wrote is:
struct cmp_by_value {
bool operator()(const test_struct_t *a, const test_struct_t *b) const
{
return *a < *b;
}
};
Now, in my main method I do the following:
testmap.insert({new test_struct_t(0, 0, 2 ), 6});
testmap.insert({new test_struct_t(0, 1, 2 ), 6});
testmap.insert({new test_struct_t(1, 1, 0 ), 6});
testmap.insert({new test_struct_t(1, 2, 0 ), 6});
testmap.insert({new test_struct_t(2, 1, 0 ), 6});
testmap.insert({new test_struct_t(1, 2, 1 ), 6});
testmap.insert({new test_struct_t(1, 2, 0 ), 6});
And then I print the values in the map with some format method:
std::string format(test_struct_t *e) {
std::stringstream ss;
ss << "(" << e->x << "," << e->y << ") = " << e->val;
return ss.str();
}
And in the main:
std::map<test_struct_t*, unsigned int>::iterator it;
for (it = testmap.begin(); it != testmap.end(); ++it) {
std::cout << format(it->first) << std::endl;
}
My program gives the following output:
(1,1) = 0
(1,2) = 0
(1,2) = 1
(2,1) = 0
(1,2) = 0
(0,0) = 2
(0,1) = 2
Can anyone explain to me why there is the duplicate entry "(1,2) k =0"? When I remove one of the other inserted statements, everything is fine and there is no duplicate. Any ideas?
EDIT: What I also found very interesting is that:
testmap[new test_struct_t(0, 0, 2 )] = 6;
testmap[new test_struct_t(0, 1, 2 )] = 6;
testmap[new test_struct_t(1, 1, 0 )] = 6;
testmap[new test_struct_t(1, 2, 0 )] = 6;
testmap[new test_struct_t(2, 1, 0 )] = 6;
testmap[new test_struct_t(1, 2, 1 )] = 6;
testmap[new test_struct_t(1, 2, 0 )] = 6;
Gives this:
(0,0) = 2
(1,1) = 0
(1,2) = 0
(0,1) = 2
Your operator< does not define a strict weak ordering. Try
bool operator<(const test_struct_t &o) const {
return std::tie(x,y,val)<std::tie(o.x,o.y,o.val);
}

Is there in OpenCV operation that is like op1:op2 in Matlab? [duplicate]

How can I do the equivalent of the following using C++/STL? I want to fill a std::vector with a range of values [min, max).
# Python
>>> x = range(0, 10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
I suppose I could use std::generate_n and provide a functor to generate the sequence, but I was wondering if there is a more succinct way of doing this using STL?
In C++11, there's std::iota:
#include <vector>
#include <numeric> //std::iota
int main() {
std::vector<int> x(10);
std::iota(std::begin(x), std::end(x), 0); //0 is the starting number
}
C++20 introduced a lazy version (just like Python) as part of the ranges library:
#include <iostream>
#include <ranges>
namespace views = std::views;
int main() {
for (int x : views::iota(0, 10)) {
std::cout << x << ' '; // 0 1 2 3 4 5 6 7 8 9
}
}
There is boost::irange:
std::vector<int> x;
boost::push_back(x, boost::irange(0, 10));
I ended up writing some utility functions to do this. You can use them as follows:
auto x = range(10); // [0, ..., 9]
auto y = range(2, 20); // [2, ..., 19]
auto z = range(10, 2, -2); // [10, 8, 6, 4]
The code:
#include <vector>
#include <stdexcept>
template <typename IntType>
std::vector<IntType> range(IntType start, IntType stop, IntType step)
{
if (step == IntType(0))
{
throw std::invalid_argument("step for range must be non-zero");
}
std::vector<IntType> result;
IntType i = start;
while ((step > 0) ? (i < stop) : (i > stop))
{
result.push_back(i);
i += step;
}
return result;
}
template <typename IntType>
std::vector<IntType> range(IntType start, IntType stop)
{
return range(start, stop, IntType(1));
}
template <typename IntType>
std::vector<IntType> range(IntType stop)
{
return range(IntType(0), stop, IntType(1));
}
I've been using this library for this exact purpose for years:
https://github.com/klmr/cpp11-range
Works very well and the proxies are optimized out.
for (auto i : range(1, 5))
cout << i << "\n";
for (auto u : range(0u))
if (u == 3u)
break;
else
cout << u << "\n";
for (auto c : range('a', 'd'))
cout << c << "\n";
for (auto i : range(100).step(-3))
if (i < 90)
break;
else
cout << i << "\n";
for (auto i : indices({"foo", "bar"}))
cout << i << '\n';
There is boost::irange, but it does not provide floating point, negative steps and can not directly initialize stl containers.
There is also numeric_range in my RO library
In RO, to initialize a vector:
vector<int> V=range(10);
Cut-n-paste example from doc page (scc - c++ snippet evaluator):
// [0,N) open-ended range. Only range from 1-arg range() is open-ended.
scc 'range(5)'
{0, 1, 2, 3, 4}
// [0,N] closed range
scc 'range(1,5)'
{1, 2, 3, 4, 5}
// floating point
scc 'range(1,5,0.5)'
{1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5}
// negative step
scc 'range(10,0,-1.5)'
{10, 8.5, 7, 5.5, 4, 2.5, 1}
// any arithmetic type
scc "range('a','z')"
a b c d e f g h i j k l m n o p q r s t u v w x y z
// no need for verbose iota. (vint - vector<int>)
scc 'vint V = range(5); V'
{0, 1, 2, 3, 4}
// is lazy
scc 'auto NR = range(1,999999999999999999l); *find(NR.begin(), NR.end(), 5)'
5
// Classic pipe. Alogorithms are from std::
scc 'vint{3,1,2,3} | sort | unique | reverse'
{3, 2, 1}
// Assign 42 to 2..5
scc 'vint V=range(0,9); range(V/2, V/5) = 42; V'
{0, 1, 42, 42, 42, 5, 6, 7, 8, 9}
// Find (brute force algorithm) maximum of `cos(x)` in interval: `8 < x < 9`:
scc 'range(8, 9, 0.01) * cos || max'
-0.1455
// Integrate sin(x) from 0 to pi
scc 'auto d=0.001; (range(0,pi,d) * sin || add) * d'
2
// Total length of strings in vector of strings
scc 'vstr V{"aaa", "bb", "cccc"}; V * size || add'
9
// Assign to c-string, then append `"XYZ"` and then remove `"bc"` substring :
scc 'char s[99]; range(s) = "abc"; (range(s) << "XYZ") - "bc"'
aXYZ
// Hide phone number:
scc "str S=\"John Q Public (650)1234567\"; S|isdigit='X'; S"
John Q Public (XXX)XXXXXXX
For those who can't use C++11 or libraries:
vector<int> x(10,0); // 0 is the starting number, 10 is the range size
transform(x.begin(),x.end(),++x.begin(),bind2nd(plus<int>(),1)); // 1 is the increment
A range() function similar to below will help:
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
// define range function (only once)
template <typename T>
vector <T> range(T N1, T N2) {
vector<T> numbers(N2-N1);
iota(numbers.begin(), numbers.end(), N1);
return numbers;
}
vector <int> arr = range(0, 10);
vector <int> arr2 = range(5, 8);
for (auto n : arr) { cout << n << " "; } cout << endl;
// output: 0 1 2 3 4 5 6 7 8 9
for (auto n : arr2) { cout << n << " "; } cout << endl;
// output: 5 6 7
I don't know of a way to do it like in python but another alternative is obviously to for loop through it:
for (int i = range1; i < range2; ++i) {
x.push_back(i);
}
chris's answer is better though if you have c++11
If you can't use C++11, you can use std::partial_sum to generate numbers from 1 to 10. And if you need numbers from 0 to 9, you can then subtract 1 using transform:
std::vector<int> my_data( 10, 1 );
std::partial_sum( my_data.begin(), my_data.end(), my_data.begin() );
std::transform(my_data.begin(), my_data.end(), my_data.begin(), bind2nd(std::minus<int>(), 1));
Some time ago I wrote the following _range class, which behaves like Python range (put it to the "range.h"):
#pragma once
#include <vector>
#include <cassert>
template < typename T = size_t >
class _range
{
const T kFrom, kEnd, kStep;
public:
///////////////////////////////////////////////////////////
// Constructor
///////////////////////////////////////////////////////////
//
// INPUT:
// from - Starting number of the sequence.
// end - Generate numbers up to, but not including this number.
// step - Difference between each number in the sequence.
//
// REMARKS:
// Parameters must be all positive or all negative
//
_range( const T from, const T end, const T step = 1 )
: kFrom( from ), kEnd( end ), kStep( step )
{
assert( kStep != 0 );
assert( ( kFrom >= 0 && kEnd > 0 && kStep > 0 ) || ( kFrom < 0 && kEnd < 0 && kStep < 0 ) );
}
// Default from==0, step==1
_range( const T end )
: kFrom( 0 ), kEnd( end ), kStep( 1 )
{
assert( kEnd > 0 );
}
public:
class _range_iter
{
T fVal;
const T kStep;
public:
_range_iter( const T v, const T step ) : fVal( v ), kStep( step ) {}
operator T () const { return fVal; }
operator const T & () { return fVal; }
const T operator * () const { return fVal; }
const _range_iter & operator ++ () { fVal += kStep; return * this; }
bool operator == ( const _range_iter & ri ) const
{
return ! operator != ( ri );
}
bool operator != ( const _range_iter & ri ) const
{
// This is a tricky part - when working with iterators
// it checks only once for != which must be a hit to stop;
// However, this does not work if increasing kStart by N times kSteps skips over kEnd
return fVal < 0 ? fVal > ri.fVal : fVal < ri.fVal;
}
};
const _range_iter begin() { return _range_iter( kFrom, kStep ); }
const _range_iter end() { return _range_iter( kEnd, kStep ); }
public:
// Conversion to any vector< T >
operator std::vector< T > ( void )
{
std::vector< T > retRange;
for( T i = kFrom; i < kEnd; i += kStep )
retRange.push_back( i );
return retRange; // use move semantics here
}
};
// A helper to use pure range meaning _range< size_t >
typedef _range<> range;
And some test code looks like the following one:
#include "range.h"
#include <iterator>
#include <fstream>
using namespace std;
void RangeTest( void )
{
ofstream ostr( "RangeTest.txt" );
if( ostr.is_open() == false )
return;
// 1:
ostr << "1st test:" << endl;
vector< float > v = _range< float >( 256 );
copy( v.begin(), v.end(), ostream_iterator< float >( ostr, ", " ) );
// 2:
ostr << endl << "2nd test:" << endl;
vector< size_t > v_size_t( range( 0, 100, 13 ) );
for( auto a : v_size_t )
ostr << a << ", ";
// 3:
ostr << endl << "3rd test:" << endl;
auto vvv = range( 123 ); // 0..122 inclusive, with step 1
for( auto a : vvv )
ostr << a << ", ";
// 4:
ostr << endl << "4th test:" << endl;
// Can be used in the nested loops as well
for( auto i : _range< float >( 0, 256, 16.5 ) )
{
for( auto j : _range< int >( -2, -16, -3 ) )
{
ostr << j << ", ";
}
ostr << endl << i << endl;
}
}
As an iterator:
#include <iostream>
class Range {
int x, y, z;
public:
Range(int x) {this->x = 0; this->y = x; this->z = 1;}
Range(int x, int y) {this->x = x; this->y = y; this->z = 1;}
Range(int x, int y, int z) {this->x = x; this->y = y; this->z = z;}
struct Iterator
{
Iterator (int val, int inc) : val{val}, inc{inc} {}
Iterator& operator++(){val+=inc; return *this;}
int operator*() const {return val;}
friend bool operator!=(const Iterator& a, const Iterator& b){return a.val < b.val;}
private:
int val, inc;
};
Iterator begin() {return Iterator(x,z);}
Iterator end() {return Iterator(y,z);}
};
int main() {
for (auto i: Range(10))
{
std::cout << i << ' '; //0 1 2 3 4 5 6 7 8 9
}
std::cout << '\n';
for (auto i: Range(1,10))
{
std::cout << i << ' '; //1 2 3 4 5 6 7 8 9
}
std::cout << '\n';
for (auto i: Range(-10,10,3))
{
std::cout << i << ' '; //-10 -7 -4 -1 2 5 8
}
return 0;
}

finding quartiles

I've written a program where the user can enter any number of values into a vector and it's supposed to return the quartiles, but I keep getting a "vector subscript out of range" error :
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <ios>
#include <vector>
int main () {
using namespace std;
cout << "Enter a list of numbers: ";
vector<double> quantile;
double x;
//invariant: homework contains all the homework grades so far
while (cin >> x)
quantile.push_back(x);
//check that the student entered some homework grades
//typedef vector<double>::size_type vec_sz;
int size = quantile.size();
if (size == 0) {
cout << endl << "You must enter your numbers . "
"Please try again." << endl;
return 1;
}
sort(quantile.begin(), quantile.end());
int mid = size/2;
double median;
median = size % 2 == 0 ? (quantile[mid] + quantile[mid-1])/2 : quantile[mid];
vector<double> first;
vector<double> third;
for (int i = 0; i!=mid; ++i)
{
first[i] = quantile[i];
}
for (int i = mid; i!= size; ++i)
{
third[i] = quantile[i];
}
double fst;
double trd;
int side_length = 0;
if (size % 2 == 0)
{
side_length = size/2;
}
else {
side_length = (size-1)/2;
}
fst = (size/2) % 2 == 0 ? (first[side_length/2]/2 + first[(side_length-1)/2])/2 : first[side_length/2];
trd = (size/2) % 2 == 0 ? (third[side_length/2]/2 + third[(side_length-1)/2])/2 : third[side_length/2];
streamsize prec = cout.precision();
cout << "The quartiles are" << setprecision(3) << "1st"
<< fst << "2nd" << median << "3rd" << trd << setprecision(prec) << endl;
return 0;
}
Instead of doing std::sort(quantile.begin(), quantile.end()) a somewhat cheaper way would be
auto const Q1 = quantile.size() / 4;
auto const Q2 = quantile.size() / 2;
auto const Q3 = Q1 + Q2;
std::nth_element(quantile.begin(), quantile.begin() + Q1, quantile.end());
std::nth_element(quantile.begin() + Q1 + 1, quantile.begin() + Q2, quantile.end());
std::nth_element(quantile.begin() + Q2 + 1, quantile.begin() + Q3, quantile.end());
This would not sort the complete array, but only do a "between groups" sort of the 4 quartile. This saves on the "within groups" sort that a full std::sort would do.
If your quantile array is not large, it's a small optimization. But the scaling behavior of std::nth_element is O(N) however, rather than O(N log N) of a std::sort.
Here is Quantile function which is MATLAB's equivalent with linear interpolation:
#include <algorithm>
#include <cmath>
#include <vector>
template<typename T>
static inline double Lerp(T v0, T v1, T t)
{
return (1 - t)*v0 + t*v1;
}
template<typename T>
static inline std::vector<T> Quantile(const std::vector<T>& inData, const std::vector<T>& probs)
{
if (inData.empty())
{
return std::vector<T>();
}
if (1 == inData.size())
{
return std::vector<T>(1, inData[0]);
}
std::vector<T> data = inData;
std::sort(data.begin(), data.end());
std::vector<T> quantiles;
for (size_t i = 0; i < probs.size(); ++i)
{
T poi = Lerp<T>(-0.5, data.size() - 0.5, probs[i]);
size_t left = std::max(int64_t(std::floor(poi)), int64_t(0));
size_t right = std::min(int64_t(std::ceil(poi)), int64_t(data.size() - 1));
T datLeft = data.at(left);
T datRight = data.at(right);
T quantile = Lerp<T>(datLeft, datRight, poi - left);
quantiles.push_back(quantile);
}
return quantiles;
}
Find quartiles:
std::vector<double> in = { 1,2,3,4,5,6,7,8,9,10,11 };
auto quartiles = Quantile<double>(in, { 0.25, 0.5, 0.75 });
This C++ template function calculates quartile for you. It assumes x to be sorted.
#include <assert.h>
template <typename T1, typename T2> typename T1::value_type quant(const T1 &x, T2 q)
{
assert(q >= 0.0 && q <= 1.0);
const auto n = x.size();
const auto id = (n - 1) * q;
const auto lo = floor(id);
const auto hi = ceil(id);
const auto qs = x[lo];
const auto h = (id - lo);
return (1.0 - h) * qs + h * x[hi];
}
To use it do:
std::vector<float> x{1,1,2,2,3,4,5,6};
std::cout << quant(x, 0.25) << std::endl;
std::cout << quant(x, 0.50) << std::endl;
std::cout << quant(x, 0.75) << std::endl;
You need to preallocate first and third vectors before you set the contents.
vector<double> first(mid);
vector<double> third(size-mid);
or use push_back instead of assignments to first[i] and third[i]
If only one element in vector, this instruction is out of range:
quantile[mid-1]
"i" starting from mid so third[0] is out of range
for (int i = mid; i!= size; ++i)
{
third[i] = quantile[i];
}
Here is one error:
vector<double> first;
vector<double> third;
for (int i = 0; i!=mid; ++i)
{
first[i] = quantile[i];
}
The vector first doesn't have any contents, but you try to access the contents. Same problem with third and its loop. Do you mean to use push_back instead?
Implementation for weighted quantiles
This implements a weight functionality for the quantile function with linear interpolation in between the gridpoints.
#include <vector>
#include <numeric>
#include <algorithm>
#include <iostream>
#include <assert.h>
// https://stackoverflow.com/a/12399290/7128154
template <typename T>
std::vector<size_t> sorted_index(const std::vector<T> &v) {
std::vector<size_t> idx(v.size());
iota(idx.begin(), idx.end(), 0);
stable_sort(idx.begin(), idx.end(),
[&v](size_t i1, size_t i2) {return v[i1] < v[i2];});
return idx;
}
// https://stackoverflow.com/a/1267878/7128154
template< typename order_iterator, typename value_iterator >
void reorder( order_iterator order_begin, order_iterator order_end, value_iterator v ) {
typedef typename std::iterator_traits< value_iterator >::value_type value_t;
typedef typename std::iterator_traits< order_iterator >::value_type index_t;
typedef typename std::iterator_traits< order_iterator >::difference_type diff_t;
diff_t remaining = order_end - 1 - order_begin;
for ( index_t s = index_t(), d; remaining > 0; ++ s ) {
for ( d = order_begin[s]; d > s; d = order_begin[d] ) ;
if ( d == s ) {
-- remaining;
value_t temp = v[s];
while ( d = order_begin[d], d != s ) {
swap( temp, v[d] );
-- remaining;
}
v[s] = temp;
}
}
}
// https://stackoverflow.com/a/1267878/7128154
template< typename order_iterator, typename value_iterator >
void reorder_destructive( order_iterator order_begin, order_iterator order_end, value_iterator v ) {
typedef typename std::iterator_traits< value_iterator >::value_type value_t;
typedef typename std::iterator_traits< order_iterator >::value_type index_t;
typedef typename std::iterator_traits< order_iterator >::difference_type diff_t;
diff_t remaining = order_end - 1 - order_begin;
for ( index_t s = index_t(); remaining > 0; ++ s ) {
index_t d = order_begin[s];
if ( d == (diff_t) -1 ) continue;
-- remaining;
value_t temp = v[s];
for ( index_t d2; d != s; d = d2 ) {
std::swap( temp, v[d] );
std::swap( order_begin[d], d2 = (diff_t) -1 );
-- remaining;
}
v[s] = temp;
}
}
// https://stackoverflow.com/a/29677616/7128154
// https://stackoverflow.com/a/37708864/7128154
template <typename T>
double quantile(double q, std::vector<T> values, std::vector<double> weights = std::vector<double>())
{
assert( 0. <= q && q <= 1. && "expecting quantile in range [0; 1]");
if (weights.empty())
{
weights = std::vector<double>(values.size(), 1.);
}
else
{
assert (values.size() == weights.size() && "values and weights missfit in quantiles");
std::vector<size_t> inds = sorted_index(values);
reorder_destructive(inds.begin(), inds.end(), weights.begin());
}
stable_sort(values.begin(), values.end());
// values and weights are sorted now
std::vector<double> quantiles (weights.size());
quantiles[0] = weights[0];
for (int ii = 1; ii < quantiles.size(); ii++)
{
quantiles[ii] = quantiles[ii-1] + weights[ii];
}
double norm = std::accumulate(weights.begin(), weights.end(), 0.0);
int ind = 0;
double qCurrent = 0;
for (; ind < quantiles.size(); ind++)
{
qCurrent = (quantiles[ind] - weights[ind] / 2. ) / norm;
quantiles[ind] = qCurrent;
if (qCurrent > q)
{
if (ind == 0) {return values[0];}
double rat = (q - quantiles[ind-1]) / (quantiles[ind] - quantiles[ind-1]);
return values[ind-1] + (values[ind] - values[ind-1]) * rat;
}
}
return values[values.size()-1];
}
template <typename T>
double quantile(double q, std::vector<T> values, std::vector<int> weights)
{
std::vector<double> weights_double (weights.begin(), weights.end());
return quantile(q, values, weights_double);
}
int main()
{
std::vector<int> vals {5, 15, 25, 35, 45, 55, 65, 75, 85, 95};
std::cout << "quantile(0, vals)=" << quantile(0, vals) << std::endl;
std::cout << "quantile(.73, vals)=" << quantile(.73, vals) << std::endl;
std::vector<int> vals2 {1, 2, 3};
std::vector<double> ws2 {1, 2, 3};
std::cout << "quantile(.13, vals2, ws2)=" << quantile(.13, vals2, ws2) << std::endl;
}
Output
quantile(0, vals)=5
quantile(.73, vals)=73
quantile(.13, vals2, ws2)=1.18667
About weighted quantiles
While in the unweighted case, the input values form an equidistant distribution
values: [1, 2, 3] -> positions: [1/6, 3/6, 5/6]
in the weighted case, the distance is modified.
values: [1, 2, 3], weights: [1, 2, 1] -> positions: [1/8, 4/8, 7/8]
This is not equivalent to a repetition of values for the unweighted case
values: [1, 2, 2, 3] -> positions: [1/8, 3/8, 5/8, 7/8],
as a plateau is formed in between the repeated values. This means:
quantile(q=3/8, values=[1, 2, 2, 3]) = 2
but
quantile(q=3/8, values=[1, 2, 3], weights=[1, 2, 1]) = 1.67