Cross product in c++

cross product, determinant
cross product example
cross product calculator
cross product identities
cross product of two arrays
java cross product
cross product of 2d vectors
cross product property

Given the following Python (from http://norvig.com/sudoku.html)

def cross(A, B):
    "Cross product of elements in A and elements in B."
    return [a+b for a in A for b in B]

cols     = '123456789'
rows     = 'ABCDEFGHI'
squares  = cross(rows, cols)

This produces:

['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'B1', 'B2', 'B3', ...]

As an exercise, I want to do the same in C++. Currently I have:

#include <iostream>
#include <map>
#include <vector>

using std::string;
using std::vector;

static vector<string> cross_string(const string &A, const string &B)
{
    vector<string> result;

    for (string::const_iterator itA = A.begin(); itA != A.end(); ++itA) {
        for (string::const_iterator itB = B.begin(); itB != B.end(); ++itB) {
            char s[] = {*itA, *itB, 0};
            result.push_back(string(s));
        }
    }
    return result;
}

int main(int argc, char** argv)
{
    const char digits[] = "123456789";
    const char rows[]   = "ABCDEFGHI";

    vector<string> res = cross_string(rows, digits);

    for (vector<string>::const_iterator it = res.begin();
         it != res.end(); ++it) {
        std::cout << *it << std::endl;
    }
}

This works, but I was hoping there would be a better way. This also does only strings, whereas the python does any list...


Edit:

Thanks for all of the replies. I accepted the one that I understood best, but Alf's answer was a close second. I note that all used C++11 and wonder whether as a novice at C++ I should adopt that directly instead of the learning the older standard. But that is perhaps best for another question.


Weirdly enough, cross_product is missing from the C++ algorithms library. It can easily be added but as Jerry’s and Alf’s answers show, opinions differ on how to do it best. In fact, I’d do it different still. Jerry’s interface conforms to that of the other C++ algorithms but he didn’t abstract away the cross product operation, which I’d do thusly:

template <typename InputIt1,
          typename InputIt2,
          typename OutputIt,
          typename F>
void cross_product(InputIt1 begin1,
                   InputIt1 end1,
                   InputIt2 begin2,
                   InputIt2 end2,
                   OutputIt out,
                   F f) {
    for (auto i = begin1; i != end1; ++i)
        for (auto j = begin2; j != end2; ++j)
            *out++ = f(*i, *j);
}

The call, in your example, would then look as follows:

auto digits = "1234546789";
auto chars = "ABCDEFGHI";
vector<string> result;

cross_product(digits, digits + strlen(digits),
              chars, chars + strlen(chars),
              back_inserter(result),
              [](char a, char b) { return string() + a + b; });

(Don’t I just love C++11? Yes, I do.)

In a proper library I’d offer a second overload which supplies a default f operation which creates a tuple similar to what Jerry’s code does. It would even be thinkable to abstract this further to allow more than two ranges – after all, the Python list comprehension allows you to iterate over more than two ranges).

Vector Cross product in C, There are two vector A and B and we have to find the dot product and cross product of two C++. filter_none. edit close. play_arrow. link brightness_4 code​  Dot product is also known as scalar product and cross product also known as vector product. Dot Product – Let we have given two vector A = a1 * i + a2 * j + a3 * k and B = b1 * i + b2 * j + b3 * k. Where i, j and k are the unit vector along the x, y and z directions.


Well it's shorter to just present the code than to explain:

#include <iostream>         // std::wcout, std::endl
#include <string>           // std::string
#include <utility>          // std::begin, std::end
#include <vector>
using namespace std;

string sum( char const a, char const b ) { return string() + a + b; }

template< class Container >
auto cross( Container const& a, Container const& b )
    -> vector< decltype( sum( *begin( a ), *begin( b ) ) ) >
{
    typedef decltype( sum( *begin( a ), *begin( b ) ) ) ResultItem;
    vector< ResultItem >   result;

    for( auto&& itemA : a ) for( auto&& itemB : b )
    {
        result.push_back( sum( itemA, itemB ) );
    }
    return result;
}

wostream& operator<<( wostream& stream, string const& s )
{
    return (stream << s.c_str());
}

template< class Item >
wostream& operator<<( wostream& stream, vector<Item> const& v )
{
    stream << "[";
    bool isFirstItem = true;
    for( auto&& item : v )
    { 
        if( !isFirstItem ) { stream << ", "; }
        stream << item;
        isFirstItem = false;
    }
    stream << "]";
    return stream;
}

int main()
{
    string const cols       = "123456789";
    string const rows       = "ABCDEFGHI";
    auto const squares      = cross( cols, rows );

    wcout << squares << endl;
}

Program for dot product and cross product of two vectors , The Cross Product a × b of two vectors is another vector that is at right angles to both: cx = aybz − azby = 3×7 − 4×6 = −3; cy = azbx − axbz = 4×5 − 2×7 = 6; cz  As b − c cannot be simultaneously parallel (for the cross product to be 0) and perpendicular (for the dot product to be 0) to a, it must be the case that b and c cancel: b = c. From the geometrical definition, the cross product is invariant under proper rotations about the axis defined by a × b .


You could certainly make this generic:

template <class InIt1, class InIt2, class OutIt>
void cross_product(InIt1 b1, InIt1 e1, InIt2 b2, InIt2 e2, OutIt out) {  
    for (auto i=b1; i != e1; ++i) 
        for (auto j=b2; j != e2; ++j) 
            *out++ = std::make_pair(*i, *j);
}

Note that you don't generally want the template parameters to be the types of the objects in the collections, but the types of iterators to the collections. For example, you could use this like this:

std::ostream &operator<<(std::ostream &os, std::pair<char, int> const &d) { 
    return os << d.first << d.second;
}

int main() { 
    std::vector<char> a{'A', 'B', 'C', 'D'};
    std::vector<int> b{ 1, 2, 3, 4};

    cross_product(a.begin(), a.end(), b.begin(), b.end(),
        infix_ostream_iterator<std::pair<char, int> >(std::cout, ", "));
    return 0;
}

...which should produce output like this:

A1, A2, A3, A4, B1, B2, B3, B4, C1, C2, C3, C4, D1, D2, D3, D4

Also note that I've used some C++11 features throughout most of this code. If you're using an older compiler (or one from Microsoft) it'll need a bit of editing.

Cross Product, C++ Program to Compute Cross Product of Two Vectors. C++Server Side ProgrammingProgramming. This is a C++ program to compute Cross  Weirdly enough, cross_product is missing from the C++ algorithms library. It can easily be added but as Jerry’s and Alf’s answers show, opinions differ on how to do it best. It can easily be added but as Jerry’s and Alf’s answers show, opinions differ on how to do it best.


templatize for classes A and B. then make pairs std::pair<A, B>

Vector products, The cross product a × b is defined as a vector c that is perpendicular (orthogonal) to both a and b, with a direction given by the right-hand rule and a magnitude  The following example shows how to use this method to calculate the cross product of two Vector structures. private Double crossProductExample() { Vector vector1 = new Vector(20, 30); Vector vector2 = new Vector(45, 70); Double crossProduct; // crossProduct is equal to 50 crossProduct = Vector.CrossProduct(vector1, vector2); return crossProduct; }


C++ Program to Compute Cross Product of Two Vectors, Cross Product. Properties of the cross product: If a, b, and c are vectors and c is a scalar, then. 1. a x b = –b x a. 2. (ca) x b = c(a x b) = a x (cb). 3. a x (b + c) = a x  We are given two vectors let’s say vector A and vector B containing x, y and directions and the task is to find the cross product and dot product of the two given vector array. What is vector? In mathematics, a quantity that has a magnitude and a direction is known as vector whereas a quantity that have only one value as magnitude is known as


Cross product, Note that the vector G = B × C is perpendicular to the plane on which vectors B and. C lie. Thus, taking the cross product of vector G with an arbitrary third vector,​  A method written in C# for calculating the cross product between two vectors: The cross product enables you to find the vector that is ‘perpendicular’ to two other vectors in 3D space. The magnitude of the resultant vector is a function of the ‘perpendicularness’ of the input vectors. Read more about the cross product here.


[PDF] Cross Product, Suppose we have three vectors →a a → , →b b → and →c c → and we form the three dimensional figure shown below. A sketch showing three  As example vector A[1, 2, 2]. Length of A is 3. B[0,0,1]. Length of B is 1. Dot product is defined? In general. They must be in the same n-dimensional space? I mean, that dot product isn't defined when we want to use it for vectors: C[A,B,C] and D[A2,B2,C2,D2]? – Tom1336 Dec 22 '13 at 21:03