How to multiply a vector and scalar in C++? - c++

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;}

Related

Vector of random integers where each integer occurs 10 times C++

#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, " "));
}

Why can't I use a set as the output collection of transform operation on a vector? [duplicate]

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)

Is there a Function to move an element in a vector to a new Position inside the same vector

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

How to copy a boost::numeric::ublas::vector to a matrix?

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;

Printing an array in C++?

Is there a way of printing arrays in C++?
I'm trying to make a function that reverses a user-input array and then prints it out. I tried Googling this problem and it seemed like C++ can't print arrays. That can't be true can it?
Just iterate over the elements. Like this:
for (int i = numElements - 1; i >= 0; i--)
cout << array[i];
Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.
Use the STL
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <ranges>
int main()
{
std::vector<int> userInput;
// Read until end of input.
// Hit control D
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(userInput)
);
// ITs 2021 now move this up as probably the best way to do it.
// Range based for is now "probably" the best alternative C++20
// As we have all the range based extension being added to the language
for(auto const& value: userInput)
{
std::cout << value << ",";
}
std::cout << "\n";
// Print the array in reverse using the range based stuff
for(auto const& value: userInput | std::views::reverse)
{
std::cout << value << ",";
}
std::cout << "\n";
// Print in Normal order
std::copy(userInput.begin(),
userInput.end(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
// Print in reverse order:
std::copy(userInput.rbegin(),
userInput.rend(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
}
May I suggest using the fish bone operator?
for (auto x = std::end(a); x != std::begin(a); )
{
std::cout <<*--x<< ' ';
}
(Can you spot it?)
Besides the for-loop based solutions, you can also use an ostream_iterator<>. Here's an example that leverages the sample code in the (now retired) SGI STL reference:
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
using namespace std;
copy(foo,
foo + sizeof(foo) / sizeof(foo[0]),
ostream_iterator<short>(cout, "\n"));
}
This generates the following:
./a.out
1
3
5
7
However, this may be overkill for your needs. A straight for-loop is probably all that you need, although litb's template sugar is quite nice, too.
Edit: Forgot the "printing in reverse" requirement. Here's one way to do it:
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
using namespace std;
reverse_iterator<short *> begin(foo + sizeof(foo) / sizeof(foo[0]));
reverse_iterator<short *> end(foo);
copy(begin,
end,
ostream_iterator<short>(cout, "\n"));
}
and the output:
$ ./a.out
7
5
3
1
Edit: C++14 update that simplifies the above code snippets using array iterator functions like std::begin() and std::rbegin():
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
// Generate array iterators using C++14 std::{r}begin()
// and std::{r}end().
// Forward
std::copy(std::begin(foo),
std::end(foo),
std::ostream_iterator<short>(std::cout, "\n"));
// Reverse
std::copy(std::rbegin(foo),
std::rend(foo),
std::ostream_iterator<short>(std::cout, "\n"));
}
There are declared arrays and arrays that are not declared, but otherwise created, particularly using new:
int *p = new int[3];
That array with 3 elements is created dynamically (and that 3 could have been calculated at runtime, too), and a pointer to it which has the size erased from its type is assigned to p. You cannot get the size anymore to print that array. A function that only receives the pointer to it can thus not print that array.
Printing declared arrays is easy. You can use sizeof to get their size and pass that size along to the function including a pointer to that array's elements. But you can also create a template that accepts the array, and deduces its size from its declared type:
template<typename Type, int Size>
void print(Type const(& array)[Size]) {
for(int i=0; i<Size; i++)
std::cout << array[i] << std::endl;
}
The problem with this is that it won't accept pointers (obviously). The easiest solution, I think, is to use std::vector. It is a dynamic, resizable "array" (with the semantics you would expect from a real one), which has a size member function:
void print(std::vector<int> const &v) {
std::vector<int>::size_type i;
for(i = 0; i<v.size(); i++)
std::cout << v[i] << std::endl;
}
You can, of course, also make this a template to accept vectors of other types.
Most of the libraries commonly used in C++ can't print arrays, per se. You'll have to loop through it manually and print out each value.
Printing arrays and dumping many different kinds of objects is a feature of higher level languages.
It certainly is! You'll have to loop through the array and print out each item individually.
This might help
//Printing The Array
for (int i = 0; i < n; i++)
{cout << numbers[i];}
n is the size of the array
std::string ss[] = { "qwerty", "asdfg", "zxcvb" };
for ( auto el : ss ) std::cout << el << '\n';
Works basically like foreach.
My simple answer is:
#include <iostream>
using namespace std;
int main()
{
int data[]{ 1, 2, 7 };
for (int i = sizeof(data) / sizeof(data[0])-1; i >= 0; i--) {
cout << data[i];
}
return 0;
}
You can use reverse iterators to print an array in reverse:
#include <iostream>
int main() {
int x[] = {1,2,3,4,5};
for (auto it = std::rbegin(x); it != std::rend(x); ++it)
std::cout << *it;
}
output
54321
If you already reversed the array, you can replace std::rbegin and std::rend with std::begin/std::end, respectively, to iterate the array in forward direction.
It's quite straightforward to copy the array's elements to a suitable output iterator. For example (using C++20 for the Ranges version):
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
template<typename T, std::size_t N>
std::ostream& print_array(std::ostream& os, std::array<T,N> const& arr)
{
std::ranges::copy(arr, std::ostream_iterator<T>(os, ", "));
return os;
}
Quick demo:
int main()
{
std::array example{ "zero", "one", "two", "three", };
print_array(std::cout, example) << '\n';
}
Of course it's more useful if we can output any kind of collection, not only arrays:
#include <algorithm>
#include <iterator>
#include <iosfwd>
#include <ranges>
template<std::ranges::input_range R>
std::ostream& print_array(std::ostream& os, R const& arr)
{
using T = std::ranges::range_value_t<R>;
std::ranges::copy(arr, std::ostream_iterator<T>(os, ", "));
return os;
}
The question mentions reversing the array for printing. That's easily achieved by using a view adapter:
print_array(std::cout, example | std::views::reverse) << '\n';
// Just do this, use a vector with this code and you're good lol -Daniel
#include <Windows.h>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<const char*> arry = { "Item 0","Item 1","Item 2","Item 3" ,"Item 4","Yay we at the end of the array"};
if (arry.size() != arry.size() || arry.empty()) {
printf("what happened to the array lol\n ");
system("PAUSE");
}
for (int i = 0; i < arry.size(); i++)
{
if (arry.max_size() == true) {
cout << "Max size of array reached!";
}
cout << "Array Value " << i << " = " << arry.at(i) << endl;
}
}
If you want to make a function that prints every single element in an array;
#include <iostream>
using namespace std;
int myArray[] = {1,2,3,4, 77, 88};
void coutArr(int *arr, int size){
for(int i=0; i<size/4; i++){
cout << arr[i] << endl;
}
}
int main(){
coutArr(myArray, sizeof(myArray));
}
The function above prints every single element in an array only, not commas etc.
You may be wondering "Why sizeoff(arr) divided by 4?". It's because cpp prints 4 if there's only a single element in an array.