I am trying to get the difference between two ranges but have little luck.
Something like
vector<int> l{ 1,5,6 };
auto diff = views::ints(1,10) - view::all( l );
==> Range<int> { 2,3,4,7,8,9 }
By the way. Are there any good writings on range-v3? Something to make me wiser?
Thanks.
You are looking for the set_difference algorithm, or its lazy view version:
#include <range/v3/view/iota.hpp>
#include <range/v3/view/set_algorithm.hpp>
#include <iostream>
#include <vector>
int main() {
std::vector<int> l{ 1,5,6 };
auto diff = ranges::view::set_difference(ranges::view::ints(1,10), l);
std::cout << diff << '\n'; // [2,3,4,7,8,9]
}
Related
I have a Sorted vector of strings and whenever a new string is added we have a function which will allow us to calculate the new position. I should be able to use this position and update the vector.
Example:
Input Vector v1{Acr,Adr,Apr,Arr,Asr};
Input New String : Aar
As soon as the String uis Added the Vector Becomes
v1{Acr,Adr,Apr,Arr,Asr,Aar};
After Addition new position is computed with a Function that Will Return position to insert I1 in this case).
So after Some operation it should become v1{Aar,Acr,Adr,Apr,Arr,Asr};
So you want to insert into an std::vector?
How about using std::vector::insert then?
Example:
v1.insert(v1.begin() + index, new_value);
As #Jarod42 commented, you could use std::lower_bound to find the insertion position, like this: C++ std::lower_bound() function to find insertion point for an index-sorted vector.
Sounds like a combination of std::vector::insert and std::lower_bound should be a good match:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main()
{
using std::vector;
using std::string;
using std::lower_bound;
using std::cout;
vector<string> v1{"Acr","Adr","Apr","Arr","Asr"};
auto insertionPoint{lower_bound(begin(v1), end(v1), "Aar")};
v1.insert(insertionPoint, "Aar");
for (auto&&s:v1) cout << s << " ";
cout << "\n";
return 0;
}
Demo
The key element is: v1.insert(insertionPoint, "Aar"); to insert directly in the right place. If you don't want to use lower_bound because you already have the index (let's call it pos for the sake of this example), you can always do sth like this v1.insert(begin(v1)+pos, "Aar");
And if you really need to append at the end initially (for whatever reason) using std::sort sounds like the most natural solution. Although the most inefficient (given you can modify the vector anyway).
Expanding the answer with custom comparison function:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
class Sth
{
std::string name_;
public:
explicit Sth(const std::string& s) : name_(s) {}
const std::string& name() const {return name_;}
};
int main(int, char*[])
{
using std::vector;
using std::string;
using std::lower_bound;
using std::cout;
vector<Sth> v1{Sth("Acr"),Sth("Adr"),Sth("Apr"),Sth("Arr"),Sth("Asr")};
auto insertionPoint{lower_bound(begin(v1), end(v1), Sth("Aar"),
[](auto&& lhs, auto&& rhs){return lhs.name() < rhs.name();})};
v1.insert(insertionPoint, Sth("Aar"));
for (auto&&s:v1) cout << s.name() << " ";
cout << "\n";
return 0;
}
Demo
If I have understood correctly you mean something like the following
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<std::string> v = { "Acr", "Adr", "Apr", "Arr", "Asr" };
v.push_back( "Aar" );
auto pos = std::upper_bound( std::begin( v ), std::prev( std::end( v ) ),
v.back() );
if ( pos != std::prev( std::end( v ) ) )
{
auto s = std::move( v.back() );
v.pop_back();
v.insert( pos, s );
}
for ( const auto &s : v )
{
std::cout << s << ' ';
}
std::cout << '\n';
return 0;
}
The program output is
Aar Acr Adr Apr Arr Asr
We have as input a vector, as an example
std::vector<std::int32_t> allnumbers{1,2,-3,4,5,-6,7,8,9};
We have a boolean condition, as an example output numbers have to be larger 3.
What we want is as output the longest subvector fullfilling the condition. All elements of the output have to have been connected in the input.
std::vector<std::int32_t> allnumbers{4,5,7,8,9};
Is wrong, as 5 and 7 have not been adjacent before (-6 between them).
std::vector<std::int32_t> allnumbers{4,5};
Is wrong, as it is not the longest subvector.
std::vector<std::int32_t> allnumbers{7,8,9};
Is finally correct.
How to write the algorithm elegantly with C++17 standard, possibly without using the Boost library? By elegantly I mean few lines of code with good readability. Utilizing prefarably as much as possible. Performance or memory consumption is here less of an issue. I think the "brute force" solution I post below already has here enough performance. One time iterate through input and only few iterators to keep track during exectuion.
The following is a working "brute force" solution:
#include <functional>
#include <iostream>
#include <stdint.h>
#include <vector>
std::vector<std::int32_t> longestConnectedVectorFullfillingPredicate(
std::function<bool(const std::int32_t)> predicate,
std::vector<std::int32_t> &inputVector)
{
auto currentIt = inputVector.begin();
auto endIt = inputVector.end();
auto beginLongestConnectedSubvector = endIt;
auto endLongestConnectedSubvector = endIt;
auto longestConnectedSubvectorLength = 0;
while (currentIt != endIt)
{
const auto currentBeginConnectedSubvector = std::find_if(
currentIt, endIt, [predicate](const std::int32_t &value) { return predicate(value); });
const auto currentEndConnectedSubvector = std::find_if(
currentBeginConnectedSubvector, endIt, [predicate](const std::int32_t &value) {
return !predicate(value);
});
const auto currentConnectedSubvectorLength =
std::distance(currentBeginConnectedSubvector, currentEndConnectedSubvector);
if (currentConnectedSubvectorLength > longestConnectedSubvectorLength)
{
longestConnectedSubvectorLength = currentConnectedSubvectorLength;
beginLongestConnectedSubvector = currentBeginConnectedSubvector;
endLongestConnectedSubvector = currentEndConnectedSubvector;
}
currentIt = currentEndConnectedSubvector;
}
return std::vector<std::int32_t>(beginLongestConnectedSubvector, endLongestConnectedSubvector);
}
int main()
{
const auto largerThree = [](std::int32_t value) { return value > 3; };
std::vector<std::int32_t> allnumbers{1, 2, -3, 4, 5, -6, 7, 8, 9};
auto result = longestConnectedVectorFullfillingPredicate(largerThree, allnumbers);
for (auto res : result)
{
std::cout << res << std::endl;
}
return 0;
}
This is quite a few lines... Would like to shorten it without loosing much readability.
You might like this, which does the following
include needed headers, define useful namespace aliases, and a couple of useful function objects
pipes allnumbers into group_by which puts all adjacent numbers greater than 3 in a range/chunk (all other numbers remain in singleton range each)
pipes that into filter which says goodby to the singletons with the number not greater than 3
then finds the longest range by using max_element to which an appropriate lambda is passed
#include <boost/hana/functional/on.hpp>
#include <boost/hana/functional/partial.hpp>
#include <boost/hana/functional/reverse_partial.hpp>
#include <boost/range/numeric.hpp>
#include <functional>
#include <iostream>
#include <range/v3/algorithm/max_element.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/filter.hpp>
#include <range/v3/view/group_by.hpp>
#include <range/v3/view/transform.hpp>
#include <vector>
using boost::hana::on;
using boost::hana::reverse_partial;
using namespace ranges::views;
using namespace ranges;
auto both = [](bool x, bool y){ return x && y; };
auto greater_than_3 = reverse_partial(std::greater<>{}, 3);
int main() {
std::vector<int> allnumbers{1,2,-3,4,5,-6,7,8,9};
auto chunks
= allnumbers
| group_by(both ^on^ greater_than_3)
| filter([](auto v){ return greater_than_3(v.front()); })
| transform(to_vector)
| to_vector;
auto result = *max_element(
chunks,
std::less<>{} ^on^ std::mem_fn(&decltype(allnumbers)::size));
for (auto i : result) {
std::cout << i << ',';
}
}
I'm trying to manipulate a set of elements in vectors in c++.
vector <int> vectorOfValue;
vectorOfValue.push_back(1);
vectorOfValue.push_back(2);
vectorOfValue.push_back(3);
vectorOfValue.push_back(4);
vectorOfValue.push_back(5);
vectorOfValue.push_back(6);
vectorOfValue.push_back(7);
vectorOfValue.push_back(8);
vectorOfValue.push_back(9);
vectorOfValue.push_back(10);
I would like to know how the program can print out the vectors of values bigger 3 and smaller than 9.
It is a set of the data to exclude the outliers for example.
If you want to use the standard library algorithms and iterators, you could use std::copy_if:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
auto main(int argc, char* argv[]) -> int
{
std::vector<int> vectorOfValue;
// code for initialization of vector ..
std::copy_if(vectorOfValue.begin(),
vectorOfValue.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[](const int value) { return value > 3 && value < 9; });
}
Short approach of mine using auto syntax instead of using iterator :
for(auto &i : vectorOfValue) {
if (i > 3 && i < 9) {
std::cout << i << std::endl;
}
}
I would like to multiply a vector with a scalar. This vector was created using the accepted answer to this question of mine namely:
std::vector<int> n(N + 1);
std::iota(begin(n), end(n), 0);
and I would like to multiply this vector, n, with a scalar (specifically of type double, if it is relevant here) called npi.
I have seen this answer to a previous question here, but it wasn't all that helpful. The way I attempted to implement it was by adding:
std::transform(n.begin(), n.end(), n.begin(),
std::bind1st(std::multiplies<T>(),pin));
to my C++ program. This returned the compile error:
error: âTâ was not declared in this scope
std::bind1st(std::multiplies<T>(),pin));
I would like to call the vector created by multiplying this vector with a scalar npi, so please do not give me code that will call this new vector n (i.e., overwriting my existing n vector).
EDIT:
If it will placate whomever voted to close this question, here is my full program:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>
#include <utility>
#include <unistd.h>
#include <algorithm>
#include <numeric>
/*#include <armadillo>*/
using namespace std;
/*using namespace arma;*/
double N = 1000.0;
double x0 = 0;
double x1 = 100;
double pin = M_PI / double(N);
int main() {
std::vector<int> n(N + 1);
std::iota(begin(n), end(n), 0);
std::transform(n.begin(), n.end(), n.begin(),
std::bind1st(std::multiplies<T>(),pin));
for(double i: n)
{
std::cout << i << '\n' << std::scientific;
}
}
For vector<int> output, one way is:
auto npi = n;
for( auto& i: npi )
i *= pin;
If npi should be vector<double> (not clear from the question) then replace the first line with:
std::vector<double> npi( n.begin(), n.end() );
You need to replace T by the type contained in the vector, in this case int. However you can probably simplify your code by using a lambda function here instead:
#include <algorithm> // for std::transform
#include <cmath> // for M_PI
#include <iostream> // for std::cout etc
#include <numeric> // for std::iota
#include <vector> // for awesome
int main() {
std::vector<int> vec1(10);
std::iota(vec1.begin(), vec1.end(), 0);
int N = 42;
std::vector<double> vec2(vec1.size()); // vec2 needs to be as big or bigger than vec1
std::transform(vec1.begin(), vec1.end(), vec2.begin(),
[N](int i) { return i * M_PI / N; });
for (auto a : vec1)
std::cout << a << " ";
std::cout << std::endl;
for (auto a : vec2)
std::cout << a << " ";
std::cout << std::endl;
}
Here's an online example: http://melpon.org/wandbox/permlink/XrNxDND0steJmym8
If I have understood you correctly you need the following
std::vector<double> v;
v.reserve(n.size());
std::transform(n.begin(), n.end(), std::back_inserter( v ),
std::bind1st(std::multiplies<double>(), pin));
You can pass the scalar in the capture clause of the Lambda function and do the multiplication inside the lambda function itself
#include <algorithm>
#include <vector>
std::vector<int> foo;
std::vector<int> bar;
auto npi=4.0;
std::transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), [&npi](auto& c){return c * npi;}
I am playing with boost::range and boost::lambda with following example to compare two numbers and get the element out which has same number.
#include <iostream>
#include <boost/optional.hpp>
#include <boost/range/algorithm/find_if.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/utility/compare_pointees.hpp>
template <class Range, class Predicate>
boost::optional<typename boost::range_value<Range>::type>
search_for(const Range& r, Predicate pred)
{
BOOST_AUTO (it, boost::find_if(r, pred));
if (it == boost::end(r))
return boost::none;
return *it;
}
int main()
{
int a = 1;
int b = 2;
int c = 3;
int d = 3;
std::vector<int*> m = {&a, &b, &c};
if (boost::optional<int*> number =
search_for(m, boost::equal_pointees(???, &d))) {
std::cout << "found:" << (*number.get()) << std::endl;
}
else {
std::cout << "not found" << std::endl;
}
}
What should I use for ??? above in search_for function?
I believe it could be very simple but don't know how to do it. I can use the boost::bind or std::bind2d, etc to compare but was thinking if there is any elegant way to do it. Also, this code sample could be restructured to much simpler one but I am just learning.
With boost::lambda, it looks like this:
namespace ll = boost::lambda;
search_for(m, *ll::_1 == d)
Which is far less complicated than taking a pointer to d just so you can use equal_pointees.