What am I doing wrong here?
// file main.cpp
#include <iostream>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
namespace ublas = boost::numeric::ublas;
int main()
{
ublas::vector<double> const v( 10 );
ublas::matrix<double> m( 1, v.size() );
ublas::matrix_row<ublas::matrix<double> > r( m, 1 );
r = v;
return 0;
}
This fails with message:
Check failed in file /usr/local/include/boost/numeric/ublas/functional.hpp at line 1370:
i < size_i
terminate called after throwing an instance of 'boost::numeric::ublas::bad_index'
what(): bad index
Aborted
However, is there more laconic way to v into m at main.cpp?
Did this not work?
std::copy(v.begin(), v.end(), m.begin1());
this will occupy the first v.size() elements of m with the value of v.
The following code compiles and runs on my system (boost 1.48 and g++ 4.62)
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <algorithm>
int main()
{
boost::numeric::ublas::vector<int> v(10);
boost::numeric::ublas::matrix<int> m(10,10); //using v.size() also works
std::copy(v.begin(), v.end(), m.begin1());
return 0;
}
Of course, you're trying to access 1st row which just isn't there for 1 x v,size() matrix. You should write:
ublas::matrix_row<ublas::matrix<double> > r( m, 0 );
though you'd be better with
row(m, 0) = v;
Related
#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// First create an instance of an engine.
random_device rnd_device;
// Specify the engine and distribution.
mt19937 mersenne_engine {rnd_device()}; // Generates random integers
uniform_int_distribution<int> dist {0, 2};
auto gen = [&dist, &mersenne_engine](){
return dist(mersenne_engine);
};
vector<int> vec(30);
generate(begin(vec), end(vec), gen);
// Optional
for (auto i : vec) {
cout << i << " ";
}
}
I am trying to create a vector of 30 numbers consisting of values 0-2 and each integer occurs 10 times. What is the most efficient way to do this in C++.
Basically it should be done as written in the comments.
First we define a std::vector with the given size
Then, we fill it with an ultra simple Lambda
And finally we shuffle it
The resulting code is simple and efficient. Please see:
#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
int main() {
// Engine to shuffle the vector
std::random_device rnd_device;
std::mt19937 me{ rnd_device() };
// Simple filler lambda
auto filler = [n = 0]() mutable->int { return n++ / 10; };
// Define vector with given size
std::vector<int> vec(30);
// Fill and shuffle
std::generate(vec.begin(), vec.end(), filler);
std::shuffle(vec.begin(), vec.end(), me);
// Debug output
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
}
This question already has answers here:
std::back_inserter for a std::set?
(2 answers)
Closed 12 months ago.
When I use transform on a set and use a vector to store the output, it works fine. But it doesn't seem to work the other way around.
This is the code that doesn't work:
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
int multiply(int a) {
return a * 2;
}
void print(int i) {
cout << i << " ";
}
int main() {
int mynumbers[] = { 3,9,2,4,1 };
vector<int> v1(mynumbers, mynumbers + 5);
set<int> s1(mynumbers, mynumbers + 5);
transform(v1.begin(), v1.end(), s1.begin(), multiply);
for_each(v1.begin(), v1.end(), print);
cout << endl;
for_each(s1.begin(), s1.end(), print);
}
As #molbdnilo pointed out:
The elements of a set are immutable.
Thus, existing elements cannot be overwritten.
However, it can be done with e.g. a std::insert_iterator:
#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5 };
std::set<int> s;
std::transform(v.begin(), v.end(),
std::insert_iterator<std::set<int>>(s, s.begin()),
[](int x) { return x * 2; });
for (int x : s) std::cout << ' ' << x;
}
Output:
2 4 6 8 10
Live demo on coliru
As #JeJo already mentioned, std::inserter can be used.
Just pasting here the code with it.
set<int> s1;
transform(v1.begin(), v1.end(), inserter(s1, s1.begin()), multiply);
For the testing purpose, it does not matter, although it is not good to initialize the set s1 with vector v1 values, because transform adds/overwrites entries in the target container, and in your code the new values are getting mixed with old values (e.g. 4,9)
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
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;}