Related
I've a vector of vectors say vector<vector<int> > items of different sizes like as follows
1,2,3
4,5
6,7,8
I want to create combinations in terms of Cartesian product of these vectors like
1,4,6
1,4,7
1,4,8
and so on till
3,5,8
How can I do that ? I've looked up several links and I've also listed them at the end of this post but I'm not able to interpret that as I'm not that familiar with the language. Could some body help me with this.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
vector<vector<int> > items;
int k = 0;
for ( int i = 0; i < 5; i++ ) {
items.push_back ( vector<int>() );
for ( int j = 0; j < 5; j++ )
items[i].push_back ( k++ );
}
cartesian ( items ); // I want some function here to do this.
}
This program has equal length vectors and I put this so that it will be easier to understand my data structure. It will be very helpful even if somebody uses others answers from other links and integrate with this to get the result. Thank you very much
Couple of links I looked at
one
Two
Program from : program
First, I'll show you a recursive version.
// Cartesion product of vector of vectors
#include <vector>
#include <iostream>
#include <iterator>
// Types to hold vector-of-ints (Vi) and vector-of-vector-of-ints (Vvi)
typedef std::vector<int> Vi;
typedef std::vector<Vi> Vvi;
// Just for the sample -- populate the intput data set
Vvi build_input() {
Vvi vvi;
for(int i = 0; i < 3; i++) {
Vi vi;
for(int j = 0; j < 3; j++) {
vi.push_back(i*10+j);
}
vvi.push_back(vi);
}
return vvi;
}
// just for the sample -- print the data sets
std::ostream&
operator<<(std::ostream& os, const Vi& vi)
{
os << "(";
std::copy(vi.begin(), vi.end(), std::ostream_iterator<int>(os, ", "));
os << ")";
return os;
}
std::ostream&
operator<<(std::ostream& os, const Vvi& vvi)
{
os << "(\n";
for(Vvi::const_iterator it = vvi.begin();
it != vvi.end();
it++) {
os << " " << *it << "\n";
}
os << ")";
return os;
}
// recursive algorithm to to produce cart. prod.
// At any given moment, "me" points to some Vi in the middle of the
// input data set.
// for int i in *me:
// add i to current result
// recurse on next "me"
//
void cart_product(
Vvi& rvvi, // final result
Vi& rvi, // current result
Vvi::const_iterator me, // current input
Vvi::const_iterator end) // final input
{
if(me == end) {
// terminal condition of the recursion. We no longer have
// any input vectors to manipulate. Add the current result (rvi)
// to the total set of results (rvvvi).
rvvi.push_back(rvi);
return;
}
// need an easy name for my vector-of-ints
const Vi& mevi = *me;
for(Vi::const_iterator it = mevi.begin();
it != mevi.end();
it++) {
// final rvi will look like "a, b, c, ME, d, e, f"
// At the moment, rvi already has "a, b, c"
rvi.push_back(*it); // add ME
cart_product(rvvi, rvi, me+1, end); add "d, e, f"
rvi.pop_back(); // clean ME off for next round
}
}
// sample only, to drive the cart_product routine.
int main() {
Vvi input(build_input());
std::cout << input << "\n";
Vvi output;
Vi outputTemp;
cart_product(output, outputTemp, input.begin(), input.end());
std::cout << output << "\n";
}
Now, I'll show you the recursive iterative version that I shamelessly stole from #John :
The rest of the program is pretty much the same, only showing the cart_product function.
// Seems like you'd want a vector of iterators
// which iterate over your individual vector<int>s.
struct Digits {
Vi::const_iterator begin;
Vi::const_iterator end;
Vi::const_iterator me;
};
typedef std::vector<Digits> Vd;
void cart_product(
Vvi& out, // final result
Vvi& in) // final result
{
Vd vd;
// Start all of the iterators at the beginning.
for(Vvi::const_iterator it = in.begin();
it != in.end();
++it) {
Digits d = {(*it).begin(), (*it).end(), (*it).begin()};
vd.push_back(d);
}
while(1) {
// Construct your first product vector by pulling
// out the element of each vector via the iterator.
Vi result;
for(Vd::const_iterator it = vd.begin();
it != vd.end();
it++) {
result.push_back(*(it->me));
}
out.push_back(result);
// Increment the rightmost one, and repeat.
// When you reach the end, reset that one to the beginning and
// increment the next-to-last one. You can get the "next-to-last"
// iterator by pulling it out of the neighboring element in your
// vector of iterators.
for(Vd::iterator it = vd.begin(); ; ) {
// okay, I started at the left instead. sue me
++(it->me);
if(it->me == it->end) {
if(it+1 == vd.end()) {
// I'm the last digit, and I'm about to roll
return;
} else {
// cascade
it->me = it->begin;
++it;
}
} else {
// normal
break;
}
}
}
}
Here is a solution in C++11.
The indexing of the variable-sized arrays can be done eloquently with modular arithmetic.
The total number of lines in the output is the product of the sizes of the input vectors. That is:
N = v[0].size() * v[1].size() * v[2].size()
Therefore the main loop has n as the iteration variable, from 0 to N-1. In principle, each value of n encodes enough information to extract each of the indices of v for that iteration. This is done in a subloop using repeated modular arithmetic:
#include <cstdlib>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
void cartesian( vector<vector<int> >& v ) {
auto product = []( long long a, vector<int>& b ) { return a*b.size(); };
const long long N = accumulate( v.begin(), v.end(), 1LL, product );
vector<int> u(v.size());
for( long long n=0 ; n<N ; ++n ) {
lldiv_t q { n, 0 };
for( long long i=v.size()-1 ; 0<=i ; --i ) {
q = div( q.quot, v[i].size() );
u[i] = v[i][q.rem];
}
// Do what you want here with u.
for( int x : u ) cout << x << ' ';
cout << '\n';
}
}
int main() {
vector<vector<int> > v { { 1, 2, 3 },
{ 4, 5 },
{ 6, 7, 8 } };
cartesian(v);
return 0;
}
Output:
1 4 6
1 4 7
1 4 8
...
3 5 8
Shorter code:
vector<vector<int>> cart_product (const vector<vector<int>>& v) {
vector<vector<int>> s = {{}};
for (const auto& u : v) {
vector<vector<int>> r;
for (const auto& x : s) {
for (const auto y : u) {
r.push_back(x);
r.back().push_back(y);
}
}
s = move(r);
}
return s;
}
Seems like you'd want a vector of iterators which iterate over your individual vector<int>s.
Start all of the iterators at the beginning. Construct your first product vector by pulling out the element of each vector via the iterator.
Increment the rightmost one, and repeat.
When you reach the end, reset that one to the beginning and increment the next-to-last one. You can get the "next-to-last" iterator by pulling it out of the neighboring element in your vector of iterators.
Continue cycling through until both the last and next-to-last iterators are at the end. Then, reset them both, increment the third-from-last iterator. In general, this can be cascaded.
It's like an odometer, but with each different digit being in a different base.
Here's my solution. Also iterative, but a little shorter than the above...
void xp(const vector<vector<int>*>& vecs, vector<vector<int>*> *result) {
vector<vector<int>*>* rslts;
for (int ii = 0; ii < vecs.size(); ++ii) {
const vector<int>& vec = *vecs[ii];
if (ii == 0) {
// vecs=[[1,2],...] ==> rslts=[[1],[2]]
rslts = new vector<vector<int>*>;
for (int jj = 0; jj < vec.size(); ++jj) {
vector<int>* v = new vector<int>;
v->push_back(vec[jj]);
rslts->push_back(v);
}
} else {
// vecs=[[1,2],[3,4],...] ==> rslts=[[1,3],[1,4],[2,3],[2,4]]
vector<vector<int>*>* tmp = new vector<vector<int>*>;
for (int jj = 0; jj < vec.size(); ++jj) { // vec[jj]=3 (first iter jj=0)
for (vector<vector<int>*>::const_iterator it = rslts->begin();
it != rslts->end(); ++it) {
vector<int>* v = new vector<int>(**it); // v=[1]
v->push_back(vec[jj]); // v=[1,3]
tmp->push_back(v); // tmp=[[1,3]]
}
}
for (int kk = 0; kk < rslts->size(); ++kk) {
delete (*rslts)[kk];
}
delete rslts;
rslts = tmp;
}
}
result->insert(result->end(), rslts->begin(), rslts->end());
delete rslts;
}
I derived it with some pain from a haskell version I wrote:
xp :: [[a]] -> [[a]]
xp [] = []
xp [l] = map (:[]) l
xp (h:t) = foldr (\x acc -> foldr (\l acc -> (x:l):acc) acc (xp t)) [] h
Since I needed the same functionality, I implemented an iterator which computes the Cartesian product on the fly, as needed, and iterates over it.
It can be used as follows.
#include <forward_list>
#include <iostream>
#include <vector>
#include "cartesian.hpp"
int main()
{
// Works with a vector of vectors
std::vector<std::vector<int>> test{{1,2,3}, {4,5,6}, {8,9}};
CartesianProduct<decltype(test)> cp(test);
for(auto const& val: cp) {
std::cout << val.at(0) << ", " << val.at(1) << ", " << val.at(2) << "\n";
}
// Also works with something much less, like a forward_list of forward_lists
std::forward_list<std::forward_list<std::string>> foo{{"boo", "far", "zab"}, {"zoo", "moo"}, {"yohoo", "bohoo", "whoot", "noo"}};
CartesianProduct<decltype(foo)> bar(foo);
for(auto const& val: bar) {
std::cout << val.at(0) << ", " << val.at(1) << ", " << val.at(2) << "\n";
}
}
The file cartesian.hpp looks like this.
#include <cassert>
#include <limits>
#include <stdexcept>
#include <vector>
#include <boost/iterator/iterator_facade.hpp>
//! Class iterating over the Cartesian product of a forward iterable container of forward iterable containers
template<typename T>
class CartesianProductIterator : public boost::iterator_facade<CartesianProductIterator<T>, std::vector<typename T::value_type::value_type> const, boost::forward_traversal_tag>
{
public:
//! Delete default constructor
CartesianProductIterator() = delete;
//! Constructor setting the underlying iterator and position
/*!
* \param[in] structure The underlying structure
* \param[in] pos The position the iterator should be initialized to. std::numeric_limits<std::size_t>::max()stands for the end, the position after the last element.
*/
explicit CartesianProductIterator(T const& structure, std::size_t pos);
private:
//! Give types more descriptive names
// \{
typedef T OuterContainer;
typedef typename T::value_type Container;
typedef typename T::value_type::value_type Content;
// \}
//! Grant access to boost::iterator_facade
friend class boost::iterator_core_access;
//! Increment iterator
void increment();
//! Check for equality
bool equal(CartesianProductIterator<T> const& other) const;
//! Dereference iterator
std::vector<Content> const& dereference() const;
//! The part we are iterating over
OuterContainer const& structure_;
//! The position in the Cartesian product
/*!
* For each element of structure_, give the position in it.
* The empty vector represents the end position.
* Note that this vector has a size equal to structure->size(), or is empty.
*/
std::vector<typename Container::const_iterator> position_;
//! The position just indexed by an integer
std::size_t absolutePosition_ = 0;
//! The begin iterators, saved for convenience and performance
std::vector<typename Container::const_iterator> cbegins_;
//! The end iterators, saved for convenience and performance
std::vector<typename Container::const_iterator> cends_;
//! Used for returning references
/*!
* We initialize with one empty element, so that we only need to add more elements in increment().
*/
mutable std::vector<std::vector<Content>> result_{std::vector<Content>()};
//! The size of the instance of OuterContainer
std::size_t size_ = 0;
};
template<typename T>
CartesianProductIterator<T>::CartesianProductIterator(OuterContainer const& structure, std::size_t pos) : structure_(structure)
{
for(auto & entry: structure_) {
cbegins_.push_back(entry.cbegin());
cends_.push_back(entry.cend());
++size_;
}
if(pos == std::numeric_limits<std::size_t>::max() || size_ == 0) {
absolutePosition_ = std::numeric_limits<std::size_t>::max();
return;
}
// Initialize with all cbegin() position
position_.reserve(size_);
for(std::size_t i = 0; i != size_; ++i) {
position_.push_back(cbegins_[i]);
if(cbegins_[i] == cends_[i]) {
// Empty member, so Cartesian product is empty
absolutePosition_ = std::numeric_limits<std::size_t>::max();
return;
}
}
// Increment to wanted position
for(std::size_t i = 0; i < pos; ++i) {
increment();
}
}
template<typename T>
void CartesianProductIterator<T>::increment()
{
if(absolutePosition_ == std::numeric_limits<std::size_t>::max()) {
return;
}
std::size_t pos = size_ - 1;
// Descend as far as necessary
while(++(position_[pos]) == cends_[pos] && pos != 0) {
--pos;
}
if(position_[pos] == cends_[pos]) {
assert(pos == 0);
absolutePosition_ = std::numeric_limits<std::size_t>::max();
return;
}
// Set all to begin behind pos
for(++pos; pos != size_; ++pos) {
position_[pos] = cbegins_[pos];
}
++absolutePosition_;
result_.emplace_back();
}
template<typename T>
std::vector<typename T::value_type::value_type> const& CartesianProductIterator<T>::dereference() const
{
if(absolutePosition_ == std::numeric_limits<std::size_t>::max()) {
throw new std::out_of_range("Out of bound dereference in CartesianProductIterator\n");
}
auto & result = result_[absolutePosition_];
if(result.empty()) {
result.reserve(size_);
for(auto & iterator: position_) {
result.push_back(*iterator);
}
}
return result;
}
template<typename T>
bool CartesianProductIterator<T>::equal(CartesianProductIterator<T> const& other) const
{
return absolutePosition_ == other.absolutePosition_ && structure_ == other.structure_;
}
//! Class that turns a forward iterable container of forward iterable containers into a forward iterable container which iterates over the Cartesian product of the forward iterable containers
template<typename T>
class CartesianProduct
{
public:
//! Constructor from type T
explicit CartesianProduct(T const& t) : t_(t) {}
//! Iterator to beginning of Cartesian product
CartesianProductIterator<T> begin() const { return CartesianProductIterator<T>(t_, 0); }
//! Iterator behind the last element of the Cartesian product
CartesianProductIterator<T> end() const { return CartesianProductIterator<T>(t_, std::numeric_limits<std::size_t>::max()); }
private:
T const& t_;
};
If someone has comments how to make it faster or better, I'd highly appreciate them.
I was just forced to implement this for a project I was working on and I came up with the code below. It can be stuck in a header and it's use is very simple but it returns all of the combinations you can get from a vector of vectors. The array that it returns only holds integers. This was a conscious decision because I just wanted the indices. In this way, I could index into each of the vector's vector and then perform the calculations I/anyone would need... best to avoid letting CartesianProduct hold "stuff" itself, it is a mathematical concept based around counting not a data structure. I'm fairly new to c++ but this was tested in a decryption algorithm pretty thoroughly. There is some light recursion but overall this is a simple implementation of a simple counting concept.
// Use of the CartesianProduct class is as follows. Give it the number
// of rows and the sizes of each of the rows. It will output all of the
// permutations of these numbers in their respective rows.
// 1. call cp.permutation() // need to check all 0s.
// 2. while cp.HasNext() // it knows the exit condition form its inputs.
// 3. cp.Increment() // Make the next permutation
// 4. cp.permutation() // get the next permutation
class CartesianProduct{
public:
CartesianProduct(int num_rows, vector<int> sizes_of_rows){
permutation_ = new int[num_rows];
num_rows_ = num_rows;
ZeroOutPermutation();
sizes_of_rows_ = sizes_of_rows;
num_max_permutations_ = 1;
for (int i = 0; i < num_rows; ++i){
num_max_permutations_ *= sizes_of_rows_[i];
}
}
~CartesianProduct(){
delete permutation_;
}
bool HasNext(){
if(num_permutations_processed_ != num_max_permutations_) {
return true;
} else {
return false;
}
}
void Increment(){
int row_to_increment = 0;
++num_permutations_processed_;
IncrementAndTest(row_to_increment);
}
int* permutation(){
return permutation_;
}
int num_permutations_processed(){
return num_permutations_processed_;
}
void PrintPermutation(){
cout << "( ";
for (int i = 0; i < num_rows_; ++i){
cout << permutation_[i] << ", ";
}
cout << " )" << endl;
}
private:
int num_permutations_processed_;
int *permutation_;
int num_rows_;
int num_max_permutations_;
vector<int> sizes_of_rows_;
// Because CartesianProduct is called first initially with it's values
// of 0 and because those values are valid and important output
// of the CartesianProduct we increment the number of permutations
// processed here when we populate the permutation_ array with 0s.
void ZeroOutPermutation(){
for (int i = 0; i < num_rows_; ++i){
permutation_[i] = 0;
}
num_permutations_processed_ = 1;
}
void IncrementAndTest(int row_to_increment){
permutation_[row_to_increment] += 1;
int max_index_of_row = sizes_of_rows_[row_to_increment] - 1;
if (permutation_[row_to_increment] > max_index_of_row){
permutation_[row_to_increment] = 0;
IncrementAndTest(row_to_increment + 1);
}
}
};
#include <iostream>
#include <vector>
void cartesian (std::vector<std::vector<int>> const& items) {
auto n = items.size();
auto next = [&](std::vector<int> & x) {
for ( int i = 0; i < n; ++ i )
if ( ++x[i] == items[i].size() ) x[i] = 0;
else return true;
return false;
};
auto print = [&](std::vector<int> const& x) {
for ( int i = 0; i < n; ++ i )
std::cout << items[i][x[i]] << ",";
std::cout << "\b \n";
};
std::vector<int> x(n);
do print(x); while (next(x)); // Shazam!
}
int main () {
std::vector<std::vector<int>>
items { { 1, 2, 3 }, { 4, 5 }, { 6, 7, 8 } };
cartesian(items);
return 0;
}
The idea behind this is as follows.
Let n := items.size().
Let m_i := items[i].size(), for all i in {0,1,...,n-1}.
Let M := {0,1,...,m_0-1} x {0,1,...,m_1-1} x ... x {0,1,...,m_{n-1}-1}.
We first solve the simpler problem of iterating through M. This is accomplished by the next lambda. The algorithm is simply the "carrying" routine grade schoolers use to add 1, albeit with a mixed radix number system.
We use this to solve the more general problem by transforming a tuple x in M to one of the desired tuples via the formula items[i][x[i]] for all i in {0,1,...,n-1}. We perform this transformation in the print lambda.
We then perform the iteration with do print(x); while (next(x));.
Now some comments on complexity, under the assumption that m_i > 1 for all i:
This algorithm requires O(n) space. Note that explicit construction of the Cartesian product takes O(m_0 m_1 m_2 ... m_{n-1}) >= O(2^n) space. So this is exponentially better on space than any algorithm which requires all tuples to be stored simultaneously in memory.
The next function takes amortized O(1) time (by a geometric series argument).
The print function takes O(n) time.
Hence, altogether, the algorithm has time complexity O(n|M|) and space complexity O(n) (not counting the cost of storing items).
An interesting thing to note is that if print is replaced with a function which inspects on average only O(1) coordinates per tuple rather than all of them, then time complexity falls to O(|M|), that is, it becomes linear time with respect to the size of the Cartesian product. In other words, avoiding the copy of the tuple each iterate can be meaningful in some situations.
This version supports no iterators or ranges, but it is a simple direct implementation that uses the multiplication operator to represent the Cartesian product, and a lambda to perform the action.
The interface is designed with the particular functionality I needed. I needed the flexibility to choose vectors over which to apply the Cartesian product in a way that did not obscure the code.
int main()
{
vector< vector<long> > v{ { 1, 2, 3 }, { 4, 5 }, { 6, 7, 8 } };
(Cartesian<long>(v[0]) * v[1] * v[2]).ForEach(
[](long p_Depth, long *p_LongList)
{
std::cout << p_LongList[0] << " " << p_LongList[1] << " " << p_LongList[2] << std::endl;
}
);
}
The implementation uses recursion up the class structure to implement the embedded for loops over each vector. The algorithm works directly on the input vectors, requiring no large temporary arrays. It is simple to understand and debug.
The use of std::function p_Action instead of void p_Action(long p_Depth, T *p_ParamList) for the lambda parameter would allow me to capture local variables, if I wanted to. In the above call, I don't.
But you knew that, didn't you. "function" is a template class which takes the type parameter of a function and makes it callable.
#include <vector>
#include <iostream>
#include <functional>
#include <string>
using namespace std;
template <class T>
class Cartesian
{
private:
vector<T> &m_Vector;
Cartesian<T> *m_Cartesian;
public:
Cartesian(vector<T> &p_Vector, Cartesian<T> *p_Cartesian=NULL)
: m_Vector(p_Vector), m_Cartesian(p_Cartesian)
{};
virtual ~Cartesian() {};
Cartesian<T> *Clone()
{
return new Cartesian<T>(m_Vector, m_Cartesian ? m_Cartesian->Clone() : NULL);
};
Cartesian<T> &operator *=(vector<T> &p_Vector)
{
if (m_Cartesian)
(*m_Cartesian) *= p_Vector;
else
m_Cartesian = new Cartesian(p_Vector);
return *this;
};
Cartesian<T> operator *(vector<T> &p_Vector)
{
return (*Clone()) *= p_Vector;
};
long Depth()
{
return m_Cartesian ? 1 + m_Cartesian->Depth() : 1;
};
void ForEach(function<void (long p_Depth, T *p_ParamList)> p_Action)
{
Loop(0, new T[Depth()], p_Action);
};
private:
void Loop(long p_Depth, T *p_ParamList, function<void (long p_Depth, T *p_ParamList)> p_Action)
{
for (T &element : m_Vector)
{
p_ParamList[p_Depth] = element;
if (m_Cartesian)
m_Cartesian->Loop(p_Depth + 1, p_ParamList, p_Action);
else
p_Action(Depth(), p_ParamList);
}
};
};
The problem arise when I am trying to write an insert function that is suppose to move all elements in the array up at the specified location given by the iterator and then insert a new value into the array at the position given by the iterator.
The code is getting errors in the insert function with the following error:
no match for 'operator[]' (operand types are 'std::basic_string [1000]' and 'std::basic_string')
I am new to using iterators, and I think that it is not possible to access array elements with pointers as indices. So I am not sure if there is another way to do this, or do I need to overload the [] operator to make it work some how?
template <class T>
class Vector {
public:
typedef T* iterator;
Vector () { }
T& operator[](unsigned int i) {
return items[i];
}
// T& operator[](iterator i) {
//return items[*i];
//}
iterator begin () {
return &items[0];
}
iterator end () {
return &items[used];
}
int size () { return used; }
iterator insert (iterator position, const T& item) {
for(Vector<T>::iterator i=&items[998]; i>=position; i--)
{
items[*(i+1)]=items[*i];
}
items[*position]= item;
return position;
}
private:
T items[1000];
int used=0;
};
This code is problematic in the sense that it creates 1000 elements of type T, even if logically it is empty. Also, if there are more than 1000 insertions, then the upper elements are discarded.
As for the compilation issues, I have tries to compile the code with Vector<int> and it compiles fine, but crashes. For the same reason it crashes with Vector<int> it does not compile with Vector<std::string>. The Issue is with the type of *i, which is , i.e., std::string in the case of Vector<std::string>. Either use iterator all the way, or use indexes, but don't mix. Using iterators:
for(Vector<T>::iterator i=&items[998]; i>=position; i--)
{
*(i+1)=*i;
}
Edit :
[Just noticed an answer by Scheff that figured this out, after completing this edit]
The above invokes undefined behavior for v.insert(v.begin(), value) since i iterates before items. To avoid that, the iteration should stop before it falls off items:
for(Vector<T>::iterator i=&items[999]; i > position; i--)
{
*i = *(i-1);
}
Also, note that the line following the loop should also be fixed:
items[*position]= item; // <--- BUG: also mixing indexes and iterators
Or using indexes:
for(int i= 998; begin() + i>=position; i--)
{
items[i+1]=items[i];
}
In addition to the answer of Michael Veksler, I tried to get it working (and hence needed a bit longer).
So, with his first proposed fix and additionally
items[*position]= item;
changed to
*position = item;
the following test compiles and runs:
#include <iostream>
int main()
{
Vector<double> vec;
vec.insert(vec.begin(), 1.0);
vec.insert(vec.begin(), 2.0);
vec.insert(vec.begin(), 3.0);
std::cout << "vec.size(): " << vec.size() << '\n';
for (int i = 0; i < vec.size(); ++i) {
std::cout << "vec[" << i << "]: " << vec[i] << '\n';
}
return 0;
}
Output:
vec.size(): 0
Oops!
The update of used is missing in insert() as well:
++used;
And, now it looks better:
vec.size(): 3
vec[0]: 3
vec[1]: 2
vec[2]: 1
The complete MCVE:
#include <iostream>
template <class T>
class Vector {
public:
typedef T* iterator;
Vector () { }
T& operator[](unsigned int i) {
return items[i];
}
// T& operator[](iterator i) {
//return items[*i];
//}
iterator begin () {
return &items[0];
}
iterator end () {
return &items[used];
}
int size () { return used; }
iterator insert (iterator position, const T& item) {
for(Vector<T>::iterator i=&items[998]; i>=position; i--)
{
*(i+1) = *i;
}
*position = item;
++used;
return position;
}
private:
T items[1000];
int used=0;
};
int main()
{
Vector<double> vec;
vec.insert(vec.begin(), 1.0);
vec.insert(vec.begin(), 2.0);
vec.insert(vec.begin(), 3.0);
std::cout << "vec.size(): " << vec.size() << '\n';
for (int i = 0; i < vec.size(); ++i) {
std::cout << "vec[" << i << "]: " << vec[i] << '\n';
}
return 0;
}
Live Demo on coliru
So you can think of an iterator in this context as essentially a glorified pointer to the elements in the array, as you defined in your typedef at the beginning of your class.
When you're trying to access the elements in your array in your insert function, you are essentially dereferencing these pointers to yield the elements themselves and THEN using those elements as indices for your array, hence producing the error that the index is of the wrong type.
So for example suppose you had a Vector<std::string>. Inside the for loop in the insert function, you have this line:
items[*(i+1)]=items[*i];
Because i is an iterator as you defined, i has the type std::string * and hence *i has the type std::string. When you then write items[*i] you are trying to use the std::string as an index for your array which you can't do.
Instead, you should use a line similar to the following:
*(i + 1) = *i
There are also a couple of logical errors in your code, but I'll leave you to find those later on.
Hope this helps!
Have a look at how std::move_backward can be implemented
template< class BidirIt1, class BidirIt2 >
BidirIt2 move_backward(BidirIt1 first, BidirIt1 last, BidirIt2 d_last)
{
while (first != last) {
*(--d_last) = std::move(*(--last));
}
return d_last;
}
You don't need to move any of the elements past end, and we can rewrite your insert to be similar
iterator insert (iterator position, const T& item) {
for(iterator i = end(), d = end() + 1; i != position; )
{
*(--d) = std::move(*(--i));
}
*position = item;
++used;
return position;
}
Note that this is undefined if you try to insert into a full Vector
I've a vector of vectors say vector<vector<int> > items of different sizes like as follows
1,2,3
4,5
6,7,8
I want to create combinations in terms of Cartesian product of these vectors like
1,4,6
1,4,7
1,4,8
and so on till
3,5,8
How can I do that ? I've looked up several links and I've also listed them at the end of this post but I'm not able to interpret that as I'm not that familiar with the language. Could some body help me with this.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
vector<vector<int> > items;
int k = 0;
for ( int i = 0; i < 5; i++ ) {
items.push_back ( vector<int>() );
for ( int j = 0; j < 5; j++ )
items[i].push_back ( k++ );
}
cartesian ( items ); // I want some function here to do this.
}
This program has equal length vectors and I put this so that it will be easier to understand my data structure. It will be very helpful even if somebody uses others answers from other links and integrate with this to get the result. Thank you very much
Couple of links I looked at
one
Two
Program from : program
First, I'll show you a recursive version.
// Cartesion product of vector of vectors
#include <vector>
#include <iostream>
#include <iterator>
// Types to hold vector-of-ints (Vi) and vector-of-vector-of-ints (Vvi)
typedef std::vector<int> Vi;
typedef std::vector<Vi> Vvi;
// Just for the sample -- populate the intput data set
Vvi build_input() {
Vvi vvi;
for(int i = 0; i < 3; i++) {
Vi vi;
for(int j = 0; j < 3; j++) {
vi.push_back(i*10+j);
}
vvi.push_back(vi);
}
return vvi;
}
// just for the sample -- print the data sets
std::ostream&
operator<<(std::ostream& os, const Vi& vi)
{
os << "(";
std::copy(vi.begin(), vi.end(), std::ostream_iterator<int>(os, ", "));
os << ")";
return os;
}
std::ostream&
operator<<(std::ostream& os, const Vvi& vvi)
{
os << "(\n";
for(Vvi::const_iterator it = vvi.begin();
it != vvi.end();
it++) {
os << " " << *it << "\n";
}
os << ")";
return os;
}
// recursive algorithm to to produce cart. prod.
// At any given moment, "me" points to some Vi in the middle of the
// input data set.
// for int i in *me:
// add i to current result
// recurse on next "me"
//
void cart_product(
Vvi& rvvi, // final result
Vi& rvi, // current result
Vvi::const_iterator me, // current input
Vvi::const_iterator end) // final input
{
if(me == end) {
// terminal condition of the recursion. We no longer have
// any input vectors to manipulate. Add the current result (rvi)
// to the total set of results (rvvvi).
rvvi.push_back(rvi);
return;
}
// need an easy name for my vector-of-ints
const Vi& mevi = *me;
for(Vi::const_iterator it = mevi.begin();
it != mevi.end();
it++) {
// final rvi will look like "a, b, c, ME, d, e, f"
// At the moment, rvi already has "a, b, c"
rvi.push_back(*it); // add ME
cart_product(rvvi, rvi, me+1, end); add "d, e, f"
rvi.pop_back(); // clean ME off for next round
}
}
// sample only, to drive the cart_product routine.
int main() {
Vvi input(build_input());
std::cout << input << "\n";
Vvi output;
Vi outputTemp;
cart_product(output, outputTemp, input.begin(), input.end());
std::cout << output << "\n";
}
Now, I'll show you the recursive iterative version that I shamelessly stole from #John :
The rest of the program is pretty much the same, only showing the cart_product function.
// Seems like you'd want a vector of iterators
// which iterate over your individual vector<int>s.
struct Digits {
Vi::const_iterator begin;
Vi::const_iterator end;
Vi::const_iterator me;
};
typedef std::vector<Digits> Vd;
void cart_product(
Vvi& out, // final result
Vvi& in) // final result
{
Vd vd;
// Start all of the iterators at the beginning.
for(Vvi::const_iterator it = in.begin();
it != in.end();
++it) {
Digits d = {(*it).begin(), (*it).end(), (*it).begin()};
vd.push_back(d);
}
while(1) {
// Construct your first product vector by pulling
// out the element of each vector via the iterator.
Vi result;
for(Vd::const_iterator it = vd.begin();
it != vd.end();
it++) {
result.push_back(*(it->me));
}
out.push_back(result);
// Increment the rightmost one, and repeat.
// When you reach the end, reset that one to the beginning and
// increment the next-to-last one. You can get the "next-to-last"
// iterator by pulling it out of the neighboring element in your
// vector of iterators.
for(Vd::iterator it = vd.begin(); ; ) {
// okay, I started at the left instead. sue me
++(it->me);
if(it->me == it->end) {
if(it+1 == vd.end()) {
// I'm the last digit, and I'm about to roll
return;
} else {
// cascade
it->me = it->begin;
++it;
}
} else {
// normal
break;
}
}
}
}
Here is a solution in C++11.
The indexing of the variable-sized arrays can be done eloquently with modular arithmetic.
The total number of lines in the output is the product of the sizes of the input vectors. That is:
N = v[0].size() * v[1].size() * v[2].size()
Therefore the main loop has n as the iteration variable, from 0 to N-1. In principle, each value of n encodes enough information to extract each of the indices of v for that iteration. This is done in a subloop using repeated modular arithmetic:
#include <cstdlib>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
void cartesian( vector<vector<int> >& v ) {
auto product = []( long long a, vector<int>& b ) { return a*b.size(); };
const long long N = accumulate( v.begin(), v.end(), 1LL, product );
vector<int> u(v.size());
for( long long n=0 ; n<N ; ++n ) {
lldiv_t q { n, 0 };
for( long long i=v.size()-1 ; 0<=i ; --i ) {
q = div( q.quot, v[i].size() );
u[i] = v[i][q.rem];
}
// Do what you want here with u.
for( int x : u ) cout << x << ' ';
cout << '\n';
}
}
int main() {
vector<vector<int> > v { { 1, 2, 3 },
{ 4, 5 },
{ 6, 7, 8 } };
cartesian(v);
return 0;
}
Output:
1 4 6
1 4 7
1 4 8
...
3 5 8
Shorter code:
vector<vector<int>> cart_product (const vector<vector<int>>& v) {
vector<vector<int>> s = {{}};
for (const auto& u : v) {
vector<vector<int>> r;
for (const auto& x : s) {
for (const auto y : u) {
r.push_back(x);
r.back().push_back(y);
}
}
s = move(r);
}
return s;
}
Seems like you'd want a vector of iterators which iterate over your individual vector<int>s.
Start all of the iterators at the beginning. Construct your first product vector by pulling out the element of each vector via the iterator.
Increment the rightmost one, and repeat.
When you reach the end, reset that one to the beginning and increment the next-to-last one. You can get the "next-to-last" iterator by pulling it out of the neighboring element in your vector of iterators.
Continue cycling through until both the last and next-to-last iterators are at the end. Then, reset them both, increment the third-from-last iterator. In general, this can be cascaded.
It's like an odometer, but with each different digit being in a different base.
Here's my solution. Also iterative, but a little shorter than the above...
void xp(const vector<vector<int>*>& vecs, vector<vector<int>*> *result) {
vector<vector<int>*>* rslts;
for (int ii = 0; ii < vecs.size(); ++ii) {
const vector<int>& vec = *vecs[ii];
if (ii == 0) {
// vecs=[[1,2],...] ==> rslts=[[1],[2]]
rslts = new vector<vector<int>*>;
for (int jj = 0; jj < vec.size(); ++jj) {
vector<int>* v = new vector<int>;
v->push_back(vec[jj]);
rslts->push_back(v);
}
} else {
// vecs=[[1,2],[3,4],...] ==> rslts=[[1,3],[1,4],[2,3],[2,4]]
vector<vector<int>*>* tmp = new vector<vector<int>*>;
for (int jj = 0; jj < vec.size(); ++jj) { // vec[jj]=3 (first iter jj=0)
for (vector<vector<int>*>::const_iterator it = rslts->begin();
it != rslts->end(); ++it) {
vector<int>* v = new vector<int>(**it); // v=[1]
v->push_back(vec[jj]); // v=[1,3]
tmp->push_back(v); // tmp=[[1,3]]
}
}
for (int kk = 0; kk < rslts->size(); ++kk) {
delete (*rslts)[kk];
}
delete rslts;
rslts = tmp;
}
}
result->insert(result->end(), rslts->begin(), rslts->end());
delete rslts;
}
I derived it with some pain from a haskell version I wrote:
xp :: [[a]] -> [[a]]
xp [] = []
xp [l] = map (:[]) l
xp (h:t) = foldr (\x acc -> foldr (\l acc -> (x:l):acc) acc (xp t)) [] h
Since I needed the same functionality, I implemented an iterator which computes the Cartesian product on the fly, as needed, and iterates over it.
It can be used as follows.
#include <forward_list>
#include <iostream>
#include <vector>
#include "cartesian.hpp"
int main()
{
// Works with a vector of vectors
std::vector<std::vector<int>> test{{1,2,3}, {4,5,6}, {8,9}};
CartesianProduct<decltype(test)> cp(test);
for(auto const& val: cp) {
std::cout << val.at(0) << ", " << val.at(1) << ", " << val.at(2) << "\n";
}
// Also works with something much less, like a forward_list of forward_lists
std::forward_list<std::forward_list<std::string>> foo{{"boo", "far", "zab"}, {"zoo", "moo"}, {"yohoo", "bohoo", "whoot", "noo"}};
CartesianProduct<decltype(foo)> bar(foo);
for(auto const& val: bar) {
std::cout << val.at(0) << ", " << val.at(1) << ", " << val.at(2) << "\n";
}
}
The file cartesian.hpp looks like this.
#include <cassert>
#include <limits>
#include <stdexcept>
#include <vector>
#include <boost/iterator/iterator_facade.hpp>
//! Class iterating over the Cartesian product of a forward iterable container of forward iterable containers
template<typename T>
class CartesianProductIterator : public boost::iterator_facade<CartesianProductIterator<T>, std::vector<typename T::value_type::value_type> const, boost::forward_traversal_tag>
{
public:
//! Delete default constructor
CartesianProductIterator() = delete;
//! Constructor setting the underlying iterator and position
/*!
* \param[in] structure The underlying structure
* \param[in] pos The position the iterator should be initialized to. std::numeric_limits<std::size_t>::max()stands for the end, the position after the last element.
*/
explicit CartesianProductIterator(T const& structure, std::size_t pos);
private:
//! Give types more descriptive names
// \{
typedef T OuterContainer;
typedef typename T::value_type Container;
typedef typename T::value_type::value_type Content;
// \}
//! Grant access to boost::iterator_facade
friend class boost::iterator_core_access;
//! Increment iterator
void increment();
//! Check for equality
bool equal(CartesianProductIterator<T> const& other) const;
//! Dereference iterator
std::vector<Content> const& dereference() const;
//! The part we are iterating over
OuterContainer const& structure_;
//! The position in the Cartesian product
/*!
* For each element of structure_, give the position in it.
* The empty vector represents the end position.
* Note that this vector has a size equal to structure->size(), or is empty.
*/
std::vector<typename Container::const_iterator> position_;
//! The position just indexed by an integer
std::size_t absolutePosition_ = 0;
//! The begin iterators, saved for convenience and performance
std::vector<typename Container::const_iterator> cbegins_;
//! The end iterators, saved for convenience and performance
std::vector<typename Container::const_iterator> cends_;
//! Used for returning references
/*!
* We initialize with one empty element, so that we only need to add more elements in increment().
*/
mutable std::vector<std::vector<Content>> result_{std::vector<Content>()};
//! The size of the instance of OuterContainer
std::size_t size_ = 0;
};
template<typename T>
CartesianProductIterator<T>::CartesianProductIterator(OuterContainer const& structure, std::size_t pos) : structure_(structure)
{
for(auto & entry: structure_) {
cbegins_.push_back(entry.cbegin());
cends_.push_back(entry.cend());
++size_;
}
if(pos == std::numeric_limits<std::size_t>::max() || size_ == 0) {
absolutePosition_ = std::numeric_limits<std::size_t>::max();
return;
}
// Initialize with all cbegin() position
position_.reserve(size_);
for(std::size_t i = 0; i != size_; ++i) {
position_.push_back(cbegins_[i]);
if(cbegins_[i] == cends_[i]) {
// Empty member, so Cartesian product is empty
absolutePosition_ = std::numeric_limits<std::size_t>::max();
return;
}
}
// Increment to wanted position
for(std::size_t i = 0; i < pos; ++i) {
increment();
}
}
template<typename T>
void CartesianProductIterator<T>::increment()
{
if(absolutePosition_ == std::numeric_limits<std::size_t>::max()) {
return;
}
std::size_t pos = size_ - 1;
// Descend as far as necessary
while(++(position_[pos]) == cends_[pos] && pos != 0) {
--pos;
}
if(position_[pos] == cends_[pos]) {
assert(pos == 0);
absolutePosition_ = std::numeric_limits<std::size_t>::max();
return;
}
// Set all to begin behind pos
for(++pos; pos != size_; ++pos) {
position_[pos] = cbegins_[pos];
}
++absolutePosition_;
result_.emplace_back();
}
template<typename T>
std::vector<typename T::value_type::value_type> const& CartesianProductIterator<T>::dereference() const
{
if(absolutePosition_ == std::numeric_limits<std::size_t>::max()) {
throw new std::out_of_range("Out of bound dereference in CartesianProductIterator\n");
}
auto & result = result_[absolutePosition_];
if(result.empty()) {
result.reserve(size_);
for(auto & iterator: position_) {
result.push_back(*iterator);
}
}
return result;
}
template<typename T>
bool CartesianProductIterator<T>::equal(CartesianProductIterator<T> const& other) const
{
return absolutePosition_ == other.absolutePosition_ && structure_ == other.structure_;
}
//! Class that turns a forward iterable container of forward iterable containers into a forward iterable container which iterates over the Cartesian product of the forward iterable containers
template<typename T>
class CartesianProduct
{
public:
//! Constructor from type T
explicit CartesianProduct(T const& t) : t_(t) {}
//! Iterator to beginning of Cartesian product
CartesianProductIterator<T> begin() const { return CartesianProductIterator<T>(t_, 0); }
//! Iterator behind the last element of the Cartesian product
CartesianProductIterator<T> end() const { return CartesianProductIterator<T>(t_, std::numeric_limits<std::size_t>::max()); }
private:
T const& t_;
};
If someone has comments how to make it faster or better, I'd highly appreciate them.
I was just forced to implement this for a project I was working on and I came up with the code below. It can be stuck in a header and it's use is very simple but it returns all of the combinations you can get from a vector of vectors. The array that it returns only holds integers. This was a conscious decision because I just wanted the indices. In this way, I could index into each of the vector's vector and then perform the calculations I/anyone would need... best to avoid letting CartesianProduct hold "stuff" itself, it is a mathematical concept based around counting not a data structure. I'm fairly new to c++ but this was tested in a decryption algorithm pretty thoroughly. There is some light recursion but overall this is a simple implementation of a simple counting concept.
// Use of the CartesianProduct class is as follows. Give it the number
// of rows and the sizes of each of the rows. It will output all of the
// permutations of these numbers in their respective rows.
// 1. call cp.permutation() // need to check all 0s.
// 2. while cp.HasNext() // it knows the exit condition form its inputs.
// 3. cp.Increment() // Make the next permutation
// 4. cp.permutation() // get the next permutation
class CartesianProduct{
public:
CartesianProduct(int num_rows, vector<int> sizes_of_rows){
permutation_ = new int[num_rows];
num_rows_ = num_rows;
ZeroOutPermutation();
sizes_of_rows_ = sizes_of_rows;
num_max_permutations_ = 1;
for (int i = 0; i < num_rows; ++i){
num_max_permutations_ *= sizes_of_rows_[i];
}
}
~CartesianProduct(){
delete permutation_;
}
bool HasNext(){
if(num_permutations_processed_ != num_max_permutations_) {
return true;
} else {
return false;
}
}
void Increment(){
int row_to_increment = 0;
++num_permutations_processed_;
IncrementAndTest(row_to_increment);
}
int* permutation(){
return permutation_;
}
int num_permutations_processed(){
return num_permutations_processed_;
}
void PrintPermutation(){
cout << "( ";
for (int i = 0; i < num_rows_; ++i){
cout << permutation_[i] << ", ";
}
cout << " )" << endl;
}
private:
int num_permutations_processed_;
int *permutation_;
int num_rows_;
int num_max_permutations_;
vector<int> sizes_of_rows_;
// Because CartesianProduct is called first initially with it's values
// of 0 and because those values are valid and important output
// of the CartesianProduct we increment the number of permutations
// processed here when we populate the permutation_ array with 0s.
void ZeroOutPermutation(){
for (int i = 0; i < num_rows_; ++i){
permutation_[i] = 0;
}
num_permutations_processed_ = 1;
}
void IncrementAndTest(int row_to_increment){
permutation_[row_to_increment] += 1;
int max_index_of_row = sizes_of_rows_[row_to_increment] - 1;
if (permutation_[row_to_increment] > max_index_of_row){
permutation_[row_to_increment] = 0;
IncrementAndTest(row_to_increment + 1);
}
}
};
#include <iostream>
#include <vector>
void cartesian (std::vector<std::vector<int>> const& items) {
auto n = items.size();
auto next = [&](std::vector<int> & x) {
for ( int i = 0; i < n; ++ i )
if ( ++x[i] == items[i].size() ) x[i] = 0;
else return true;
return false;
};
auto print = [&](std::vector<int> const& x) {
for ( int i = 0; i < n; ++ i )
std::cout << items[i][x[i]] << ",";
std::cout << "\b \n";
};
std::vector<int> x(n);
do print(x); while (next(x)); // Shazam!
}
int main () {
std::vector<std::vector<int>>
items { { 1, 2, 3 }, { 4, 5 }, { 6, 7, 8 } };
cartesian(items);
return 0;
}
The idea behind this is as follows.
Let n := items.size().
Let m_i := items[i].size(), for all i in {0,1,...,n-1}.
Let M := {0,1,...,m_0-1} x {0,1,...,m_1-1} x ... x {0,1,...,m_{n-1}-1}.
We first solve the simpler problem of iterating through M. This is accomplished by the next lambda. The algorithm is simply the "carrying" routine grade schoolers use to add 1, albeit with a mixed radix number system.
We use this to solve the more general problem by transforming a tuple x in M to one of the desired tuples via the formula items[i][x[i]] for all i in {0,1,...,n-1}. We perform this transformation in the print lambda.
We then perform the iteration with do print(x); while (next(x));.
Now some comments on complexity, under the assumption that m_i > 1 for all i:
This algorithm requires O(n) space. Note that explicit construction of the Cartesian product takes O(m_0 m_1 m_2 ... m_{n-1}) >= O(2^n) space. So this is exponentially better on space than any algorithm which requires all tuples to be stored simultaneously in memory.
The next function takes amortized O(1) time (by a geometric series argument).
The print function takes O(n) time.
Hence, altogether, the algorithm has time complexity O(n|M|) and space complexity O(n) (not counting the cost of storing items).
An interesting thing to note is that if print is replaced with a function which inspects on average only O(1) coordinates per tuple rather than all of them, then time complexity falls to O(|M|), that is, it becomes linear time with respect to the size of the Cartesian product. In other words, avoiding the copy of the tuple each iterate can be meaningful in some situations.
This version supports no iterators or ranges, but it is a simple direct implementation that uses the multiplication operator to represent the Cartesian product, and a lambda to perform the action.
The interface is designed with the particular functionality I needed. I needed the flexibility to choose vectors over which to apply the Cartesian product in a way that did not obscure the code.
int main()
{
vector< vector<long> > v{ { 1, 2, 3 }, { 4, 5 }, { 6, 7, 8 } };
(Cartesian<long>(v[0]) * v[1] * v[2]).ForEach(
[](long p_Depth, long *p_LongList)
{
std::cout << p_LongList[0] << " " << p_LongList[1] << " " << p_LongList[2] << std::endl;
}
);
}
The implementation uses recursion up the class structure to implement the embedded for loops over each vector. The algorithm works directly on the input vectors, requiring no large temporary arrays. It is simple to understand and debug.
The use of std::function p_Action instead of void p_Action(long p_Depth, T *p_ParamList) for the lambda parameter would allow me to capture local variables, if I wanted to. In the above call, I don't.
But you knew that, didn't you. "function" is a template class which takes the type parameter of a function and makes it callable.
#include <vector>
#include <iostream>
#include <functional>
#include <string>
using namespace std;
template <class T>
class Cartesian
{
private:
vector<T> &m_Vector;
Cartesian<T> *m_Cartesian;
public:
Cartesian(vector<T> &p_Vector, Cartesian<T> *p_Cartesian=NULL)
: m_Vector(p_Vector), m_Cartesian(p_Cartesian)
{};
virtual ~Cartesian() {};
Cartesian<T> *Clone()
{
return new Cartesian<T>(m_Vector, m_Cartesian ? m_Cartesian->Clone() : NULL);
};
Cartesian<T> &operator *=(vector<T> &p_Vector)
{
if (m_Cartesian)
(*m_Cartesian) *= p_Vector;
else
m_Cartesian = new Cartesian(p_Vector);
return *this;
};
Cartesian<T> operator *(vector<T> &p_Vector)
{
return (*Clone()) *= p_Vector;
};
long Depth()
{
return m_Cartesian ? 1 + m_Cartesian->Depth() : 1;
};
void ForEach(function<void (long p_Depth, T *p_ParamList)> p_Action)
{
Loop(0, new T[Depth()], p_Action);
};
private:
void Loop(long p_Depth, T *p_ParamList, function<void (long p_Depth, T *p_ParamList)> p_Action)
{
for (T &element : m_Vector)
{
p_ParamList[p_Depth] = element;
if (m_Cartesian)
m_Cartesian->Loop(p_Depth + 1, p_ParamList, p_Action);
else
p_Action(Depth(), p_ParamList);
}
};
};
I've a vector of vectors say vector<vector<int> > items of different sizes like as follows
1,2,3
4,5
6,7,8
I want to create combinations in terms of Cartesian product of these vectors like
1,4,6
1,4,7
1,4,8
and so on till
3,5,8
How can I do that ? I've looked up several links and I've also listed them at the end of this post but I'm not able to interpret that as I'm not that familiar with the language. Could some body help me with this.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
vector<vector<int> > items;
int k = 0;
for ( int i = 0; i < 5; i++ ) {
items.push_back ( vector<int>() );
for ( int j = 0; j < 5; j++ )
items[i].push_back ( k++ );
}
cartesian ( items ); // I want some function here to do this.
}
This program has equal length vectors and I put this so that it will be easier to understand my data structure. It will be very helpful even if somebody uses others answers from other links and integrate with this to get the result. Thank you very much
Couple of links I looked at
one
Two
Program from : program
First, I'll show you a recursive version.
// Cartesion product of vector of vectors
#include <vector>
#include <iostream>
#include <iterator>
// Types to hold vector-of-ints (Vi) and vector-of-vector-of-ints (Vvi)
typedef std::vector<int> Vi;
typedef std::vector<Vi> Vvi;
// Just for the sample -- populate the intput data set
Vvi build_input() {
Vvi vvi;
for(int i = 0; i < 3; i++) {
Vi vi;
for(int j = 0; j < 3; j++) {
vi.push_back(i*10+j);
}
vvi.push_back(vi);
}
return vvi;
}
// just for the sample -- print the data sets
std::ostream&
operator<<(std::ostream& os, const Vi& vi)
{
os << "(";
std::copy(vi.begin(), vi.end(), std::ostream_iterator<int>(os, ", "));
os << ")";
return os;
}
std::ostream&
operator<<(std::ostream& os, const Vvi& vvi)
{
os << "(\n";
for(Vvi::const_iterator it = vvi.begin();
it != vvi.end();
it++) {
os << " " << *it << "\n";
}
os << ")";
return os;
}
// recursive algorithm to to produce cart. prod.
// At any given moment, "me" points to some Vi in the middle of the
// input data set.
// for int i in *me:
// add i to current result
// recurse on next "me"
//
void cart_product(
Vvi& rvvi, // final result
Vi& rvi, // current result
Vvi::const_iterator me, // current input
Vvi::const_iterator end) // final input
{
if(me == end) {
// terminal condition of the recursion. We no longer have
// any input vectors to manipulate. Add the current result (rvi)
// to the total set of results (rvvvi).
rvvi.push_back(rvi);
return;
}
// need an easy name for my vector-of-ints
const Vi& mevi = *me;
for(Vi::const_iterator it = mevi.begin();
it != mevi.end();
it++) {
// final rvi will look like "a, b, c, ME, d, e, f"
// At the moment, rvi already has "a, b, c"
rvi.push_back(*it); // add ME
cart_product(rvvi, rvi, me+1, end); add "d, e, f"
rvi.pop_back(); // clean ME off for next round
}
}
// sample only, to drive the cart_product routine.
int main() {
Vvi input(build_input());
std::cout << input << "\n";
Vvi output;
Vi outputTemp;
cart_product(output, outputTemp, input.begin(), input.end());
std::cout << output << "\n";
}
Now, I'll show you the recursive iterative version that I shamelessly stole from #John :
The rest of the program is pretty much the same, only showing the cart_product function.
// Seems like you'd want a vector of iterators
// which iterate over your individual vector<int>s.
struct Digits {
Vi::const_iterator begin;
Vi::const_iterator end;
Vi::const_iterator me;
};
typedef std::vector<Digits> Vd;
void cart_product(
Vvi& out, // final result
Vvi& in) // final result
{
Vd vd;
// Start all of the iterators at the beginning.
for(Vvi::const_iterator it = in.begin();
it != in.end();
++it) {
Digits d = {(*it).begin(), (*it).end(), (*it).begin()};
vd.push_back(d);
}
while(1) {
// Construct your first product vector by pulling
// out the element of each vector via the iterator.
Vi result;
for(Vd::const_iterator it = vd.begin();
it != vd.end();
it++) {
result.push_back(*(it->me));
}
out.push_back(result);
// Increment the rightmost one, and repeat.
// When you reach the end, reset that one to the beginning and
// increment the next-to-last one. You can get the "next-to-last"
// iterator by pulling it out of the neighboring element in your
// vector of iterators.
for(Vd::iterator it = vd.begin(); ; ) {
// okay, I started at the left instead. sue me
++(it->me);
if(it->me == it->end) {
if(it+1 == vd.end()) {
// I'm the last digit, and I'm about to roll
return;
} else {
// cascade
it->me = it->begin;
++it;
}
} else {
// normal
break;
}
}
}
}
Here is a solution in C++11.
The indexing of the variable-sized arrays can be done eloquently with modular arithmetic.
The total number of lines in the output is the product of the sizes of the input vectors. That is:
N = v[0].size() * v[1].size() * v[2].size()
Therefore the main loop has n as the iteration variable, from 0 to N-1. In principle, each value of n encodes enough information to extract each of the indices of v for that iteration. This is done in a subloop using repeated modular arithmetic:
#include <cstdlib>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
void cartesian( vector<vector<int> >& v ) {
auto product = []( long long a, vector<int>& b ) { return a*b.size(); };
const long long N = accumulate( v.begin(), v.end(), 1LL, product );
vector<int> u(v.size());
for( long long n=0 ; n<N ; ++n ) {
lldiv_t q { n, 0 };
for( long long i=v.size()-1 ; 0<=i ; --i ) {
q = div( q.quot, v[i].size() );
u[i] = v[i][q.rem];
}
// Do what you want here with u.
for( int x : u ) cout << x << ' ';
cout << '\n';
}
}
int main() {
vector<vector<int> > v { { 1, 2, 3 },
{ 4, 5 },
{ 6, 7, 8 } };
cartesian(v);
return 0;
}
Output:
1 4 6
1 4 7
1 4 8
...
3 5 8
Shorter code:
vector<vector<int>> cart_product (const vector<vector<int>>& v) {
vector<vector<int>> s = {{}};
for (const auto& u : v) {
vector<vector<int>> r;
for (const auto& x : s) {
for (const auto y : u) {
r.push_back(x);
r.back().push_back(y);
}
}
s = move(r);
}
return s;
}
Seems like you'd want a vector of iterators which iterate over your individual vector<int>s.
Start all of the iterators at the beginning. Construct your first product vector by pulling out the element of each vector via the iterator.
Increment the rightmost one, and repeat.
When you reach the end, reset that one to the beginning and increment the next-to-last one. You can get the "next-to-last" iterator by pulling it out of the neighboring element in your vector of iterators.
Continue cycling through until both the last and next-to-last iterators are at the end. Then, reset them both, increment the third-from-last iterator. In general, this can be cascaded.
It's like an odometer, but with each different digit being in a different base.
Here's my solution. Also iterative, but a little shorter than the above...
void xp(const vector<vector<int>*>& vecs, vector<vector<int>*> *result) {
vector<vector<int>*>* rslts;
for (int ii = 0; ii < vecs.size(); ++ii) {
const vector<int>& vec = *vecs[ii];
if (ii == 0) {
// vecs=[[1,2],...] ==> rslts=[[1],[2]]
rslts = new vector<vector<int>*>;
for (int jj = 0; jj < vec.size(); ++jj) {
vector<int>* v = new vector<int>;
v->push_back(vec[jj]);
rslts->push_back(v);
}
} else {
// vecs=[[1,2],[3,4],...] ==> rslts=[[1,3],[1,4],[2,3],[2,4]]
vector<vector<int>*>* tmp = new vector<vector<int>*>;
for (int jj = 0; jj < vec.size(); ++jj) { // vec[jj]=3 (first iter jj=0)
for (vector<vector<int>*>::const_iterator it = rslts->begin();
it != rslts->end(); ++it) {
vector<int>* v = new vector<int>(**it); // v=[1]
v->push_back(vec[jj]); // v=[1,3]
tmp->push_back(v); // tmp=[[1,3]]
}
}
for (int kk = 0; kk < rslts->size(); ++kk) {
delete (*rslts)[kk];
}
delete rslts;
rslts = tmp;
}
}
result->insert(result->end(), rslts->begin(), rslts->end());
delete rslts;
}
I derived it with some pain from a haskell version I wrote:
xp :: [[a]] -> [[a]]
xp [] = []
xp [l] = map (:[]) l
xp (h:t) = foldr (\x acc -> foldr (\l acc -> (x:l):acc) acc (xp t)) [] h
Since I needed the same functionality, I implemented an iterator which computes the Cartesian product on the fly, as needed, and iterates over it.
It can be used as follows.
#include <forward_list>
#include <iostream>
#include <vector>
#include "cartesian.hpp"
int main()
{
// Works with a vector of vectors
std::vector<std::vector<int>> test{{1,2,3}, {4,5,6}, {8,9}};
CartesianProduct<decltype(test)> cp(test);
for(auto const& val: cp) {
std::cout << val.at(0) << ", " << val.at(1) << ", " << val.at(2) << "\n";
}
// Also works with something much less, like a forward_list of forward_lists
std::forward_list<std::forward_list<std::string>> foo{{"boo", "far", "zab"}, {"zoo", "moo"}, {"yohoo", "bohoo", "whoot", "noo"}};
CartesianProduct<decltype(foo)> bar(foo);
for(auto const& val: bar) {
std::cout << val.at(0) << ", " << val.at(1) << ", " << val.at(2) << "\n";
}
}
The file cartesian.hpp looks like this.
#include <cassert>
#include <limits>
#include <stdexcept>
#include <vector>
#include <boost/iterator/iterator_facade.hpp>
//! Class iterating over the Cartesian product of a forward iterable container of forward iterable containers
template<typename T>
class CartesianProductIterator : public boost::iterator_facade<CartesianProductIterator<T>, std::vector<typename T::value_type::value_type> const, boost::forward_traversal_tag>
{
public:
//! Delete default constructor
CartesianProductIterator() = delete;
//! Constructor setting the underlying iterator and position
/*!
* \param[in] structure The underlying structure
* \param[in] pos The position the iterator should be initialized to. std::numeric_limits<std::size_t>::max()stands for the end, the position after the last element.
*/
explicit CartesianProductIterator(T const& structure, std::size_t pos);
private:
//! Give types more descriptive names
// \{
typedef T OuterContainer;
typedef typename T::value_type Container;
typedef typename T::value_type::value_type Content;
// \}
//! Grant access to boost::iterator_facade
friend class boost::iterator_core_access;
//! Increment iterator
void increment();
//! Check for equality
bool equal(CartesianProductIterator<T> const& other) const;
//! Dereference iterator
std::vector<Content> const& dereference() const;
//! The part we are iterating over
OuterContainer const& structure_;
//! The position in the Cartesian product
/*!
* For each element of structure_, give the position in it.
* The empty vector represents the end position.
* Note that this vector has a size equal to structure->size(), or is empty.
*/
std::vector<typename Container::const_iterator> position_;
//! The position just indexed by an integer
std::size_t absolutePosition_ = 0;
//! The begin iterators, saved for convenience and performance
std::vector<typename Container::const_iterator> cbegins_;
//! The end iterators, saved for convenience and performance
std::vector<typename Container::const_iterator> cends_;
//! Used for returning references
/*!
* We initialize with one empty element, so that we only need to add more elements in increment().
*/
mutable std::vector<std::vector<Content>> result_{std::vector<Content>()};
//! The size of the instance of OuterContainer
std::size_t size_ = 0;
};
template<typename T>
CartesianProductIterator<T>::CartesianProductIterator(OuterContainer const& structure, std::size_t pos) : structure_(structure)
{
for(auto & entry: structure_) {
cbegins_.push_back(entry.cbegin());
cends_.push_back(entry.cend());
++size_;
}
if(pos == std::numeric_limits<std::size_t>::max() || size_ == 0) {
absolutePosition_ = std::numeric_limits<std::size_t>::max();
return;
}
// Initialize with all cbegin() position
position_.reserve(size_);
for(std::size_t i = 0; i != size_; ++i) {
position_.push_back(cbegins_[i]);
if(cbegins_[i] == cends_[i]) {
// Empty member, so Cartesian product is empty
absolutePosition_ = std::numeric_limits<std::size_t>::max();
return;
}
}
// Increment to wanted position
for(std::size_t i = 0; i < pos; ++i) {
increment();
}
}
template<typename T>
void CartesianProductIterator<T>::increment()
{
if(absolutePosition_ == std::numeric_limits<std::size_t>::max()) {
return;
}
std::size_t pos = size_ - 1;
// Descend as far as necessary
while(++(position_[pos]) == cends_[pos] && pos != 0) {
--pos;
}
if(position_[pos] == cends_[pos]) {
assert(pos == 0);
absolutePosition_ = std::numeric_limits<std::size_t>::max();
return;
}
// Set all to begin behind pos
for(++pos; pos != size_; ++pos) {
position_[pos] = cbegins_[pos];
}
++absolutePosition_;
result_.emplace_back();
}
template<typename T>
std::vector<typename T::value_type::value_type> const& CartesianProductIterator<T>::dereference() const
{
if(absolutePosition_ == std::numeric_limits<std::size_t>::max()) {
throw new std::out_of_range("Out of bound dereference in CartesianProductIterator\n");
}
auto & result = result_[absolutePosition_];
if(result.empty()) {
result.reserve(size_);
for(auto & iterator: position_) {
result.push_back(*iterator);
}
}
return result;
}
template<typename T>
bool CartesianProductIterator<T>::equal(CartesianProductIterator<T> const& other) const
{
return absolutePosition_ == other.absolutePosition_ && structure_ == other.structure_;
}
//! Class that turns a forward iterable container of forward iterable containers into a forward iterable container which iterates over the Cartesian product of the forward iterable containers
template<typename T>
class CartesianProduct
{
public:
//! Constructor from type T
explicit CartesianProduct(T const& t) : t_(t) {}
//! Iterator to beginning of Cartesian product
CartesianProductIterator<T> begin() const { return CartesianProductIterator<T>(t_, 0); }
//! Iterator behind the last element of the Cartesian product
CartesianProductIterator<T> end() const { return CartesianProductIterator<T>(t_, std::numeric_limits<std::size_t>::max()); }
private:
T const& t_;
};
If someone has comments how to make it faster or better, I'd highly appreciate them.
I was just forced to implement this for a project I was working on and I came up with the code below. It can be stuck in a header and it's use is very simple but it returns all of the combinations you can get from a vector of vectors. The array that it returns only holds integers. This was a conscious decision because I just wanted the indices. In this way, I could index into each of the vector's vector and then perform the calculations I/anyone would need... best to avoid letting CartesianProduct hold "stuff" itself, it is a mathematical concept based around counting not a data structure. I'm fairly new to c++ but this was tested in a decryption algorithm pretty thoroughly. There is some light recursion but overall this is a simple implementation of a simple counting concept.
// Use of the CartesianProduct class is as follows. Give it the number
// of rows and the sizes of each of the rows. It will output all of the
// permutations of these numbers in their respective rows.
// 1. call cp.permutation() // need to check all 0s.
// 2. while cp.HasNext() // it knows the exit condition form its inputs.
// 3. cp.Increment() // Make the next permutation
// 4. cp.permutation() // get the next permutation
class CartesianProduct{
public:
CartesianProduct(int num_rows, vector<int> sizes_of_rows){
permutation_ = new int[num_rows];
num_rows_ = num_rows;
ZeroOutPermutation();
sizes_of_rows_ = sizes_of_rows;
num_max_permutations_ = 1;
for (int i = 0; i < num_rows; ++i){
num_max_permutations_ *= sizes_of_rows_[i];
}
}
~CartesianProduct(){
delete permutation_;
}
bool HasNext(){
if(num_permutations_processed_ != num_max_permutations_) {
return true;
} else {
return false;
}
}
void Increment(){
int row_to_increment = 0;
++num_permutations_processed_;
IncrementAndTest(row_to_increment);
}
int* permutation(){
return permutation_;
}
int num_permutations_processed(){
return num_permutations_processed_;
}
void PrintPermutation(){
cout << "( ";
for (int i = 0; i < num_rows_; ++i){
cout << permutation_[i] << ", ";
}
cout << " )" << endl;
}
private:
int num_permutations_processed_;
int *permutation_;
int num_rows_;
int num_max_permutations_;
vector<int> sizes_of_rows_;
// Because CartesianProduct is called first initially with it's values
// of 0 and because those values are valid and important output
// of the CartesianProduct we increment the number of permutations
// processed here when we populate the permutation_ array with 0s.
void ZeroOutPermutation(){
for (int i = 0; i < num_rows_; ++i){
permutation_[i] = 0;
}
num_permutations_processed_ = 1;
}
void IncrementAndTest(int row_to_increment){
permutation_[row_to_increment] += 1;
int max_index_of_row = sizes_of_rows_[row_to_increment] - 1;
if (permutation_[row_to_increment] > max_index_of_row){
permutation_[row_to_increment] = 0;
IncrementAndTest(row_to_increment + 1);
}
}
};
#include <iostream>
#include <vector>
void cartesian (std::vector<std::vector<int>> const& items) {
auto n = items.size();
auto next = [&](std::vector<int> & x) {
for ( int i = 0; i < n; ++ i )
if ( ++x[i] == items[i].size() ) x[i] = 0;
else return true;
return false;
};
auto print = [&](std::vector<int> const& x) {
for ( int i = 0; i < n; ++ i )
std::cout << items[i][x[i]] << ",";
std::cout << "\b \n";
};
std::vector<int> x(n);
do print(x); while (next(x)); // Shazam!
}
int main () {
std::vector<std::vector<int>>
items { { 1, 2, 3 }, { 4, 5 }, { 6, 7, 8 } };
cartesian(items);
return 0;
}
The idea behind this is as follows.
Let n := items.size().
Let m_i := items[i].size(), for all i in {0,1,...,n-1}.
Let M := {0,1,...,m_0-1} x {0,1,...,m_1-1} x ... x {0,1,...,m_{n-1}-1}.
We first solve the simpler problem of iterating through M. This is accomplished by the next lambda. The algorithm is simply the "carrying" routine grade schoolers use to add 1, albeit with a mixed radix number system.
We use this to solve the more general problem by transforming a tuple x in M to one of the desired tuples via the formula items[i][x[i]] for all i in {0,1,...,n-1}. We perform this transformation in the print lambda.
We then perform the iteration with do print(x); while (next(x));.
Now some comments on complexity, under the assumption that m_i > 1 for all i:
This algorithm requires O(n) space. Note that explicit construction of the Cartesian product takes O(m_0 m_1 m_2 ... m_{n-1}) >= O(2^n) space. So this is exponentially better on space than any algorithm which requires all tuples to be stored simultaneously in memory.
The next function takes amortized O(1) time (by a geometric series argument).
The print function takes O(n) time.
Hence, altogether, the algorithm has time complexity O(n|M|) and space complexity O(n) (not counting the cost of storing items).
An interesting thing to note is that if print is replaced with a function which inspects on average only O(1) coordinates per tuple rather than all of them, then time complexity falls to O(|M|), that is, it becomes linear time with respect to the size of the Cartesian product. In other words, avoiding the copy of the tuple each iterate can be meaningful in some situations.
This version supports no iterators or ranges, but it is a simple direct implementation that uses the multiplication operator to represent the Cartesian product, and a lambda to perform the action.
The interface is designed with the particular functionality I needed. I needed the flexibility to choose vectors over which to apply the Cartesian product in a way that did not obscure the code.
int main()
{
vector< vector<long> > v{ { 1, 2, 3 }, { 4, 5 }, { 6, 7, 8 } };
(Cartesian<long>(v[0]) * v[1] * v[2]).ForEach(
[](long p_Depth, long *p_LongList)
{
std::cout << p_LongList[0] << " " << p_LongList[1] << " " << p_LongList[2] << std::endl;
}
);
}
The implementation uses recursion up the class structure to implement the embedded for loops over each vector. The algorithm works directly on the input vectors, requiring no large temporary arrays. It is simple to understand and debug.
The use of std::function p_Action instead of void p_Action(long p_Depth, T *p_ParamList) for the lambda parameter would allow me to capture local variables, if I wanted to. In the above call, I don't.
But you knew that, didn't you. "function" is a template class which takes the type parameter of a function and makes it callable.
#include <vector>
#include <iostream>
#include <functional>
#include <string>
using namespace std;
template <class T>
class Cartesian
{
private:
vector<T> &m_Vector;
Cartesian<T> *m_Cartesian;
public:
Cartesian(vector<T> &p_Vector, Cartesian<T> *p_Cartesian=NULL)
: m_Vector(p_Vector), m_Cartesian(p_Cartesian)
{};
virtual ~Cartesian() {};
Cartesian<T> *Clone()
{
return new Cartesian<T>(m_Vector, m_Cartesian ? m_Cartesian->Clone() : NULL);
};
Cartesian<T> &operator *=(vector<T> &p_Vector)
{
if (m_Cartesian)
(*m_Cartesian) *= p_Vector;
else
m_Cartesian = new Cartesian(p_Vector);
return *this;
};
Cartesian<T> operator *(vector<T> &p_Vector)
{
return (*Clone()) *= p_Vector;
};
long Depth()
{
return m_Cartesian ? 1 + m_Cartesian->Depth() : 1;
};
void ForEach(function<void (long p_Depth, T *p_ParamList)> p_Action)
{
Loop(0, new T[Depth()], p_Action);
};
private:
void Loop(long p_Depth, T *p_ParamList, function<void (long p_Depth, T *p_ParamList)> p_Action)
{
for (T &element : m_Vector)
{
p_ParamList[p_Depth] = element;
if (m_Cartesian)
m_Cartesian->Loop(p_Depth + 1, p_ParamList, p_Action);
else
p_Action(Depth(), p_ParamList);
}
};
};
I need to find an element position in an std::vector to use it for referencing an element in another vector:
int find( const vector<type>& where, int searchParameter )
{
for( int i = 0; i < where.size(); i++ ) {
if( conditionMet( where[i], searchParameter ) ) {
return i;
}
}
return -1;
}
// caller:
const int position = find( firstVector, parameter );
if( position != -1 ) {
doAction( secondVector[position] );
}
however vector::size() returns size_t which corresponds to an unsigned integral type that can't directly store -1. How do I signal that the element is not found in a vector when using size_t instead of int as an index?
Take a look at the answers provided for this question: Invalid value for size_t?. Also you can use std::find_if with std::distance to get the index.
std::vector<type>::iterator iter = std::find_if(vec.begin(), vec.end(), comparisonFunc);
size_t index = std::distance(vec.begin(), iter);
if(index == vec.size())
{
//invalid
}
First of all, do you really need to store indices like this? Have you looked into std::map, enabling you to store key => value pairs?
Secondly, if you used iterators instead, you would be able to return std::vector.end() to indicate an invalid result. To convert an iterator to an index you simply use
size_t i = it - myvector.begin();
You could use std::numeric_limits<size_t>::max() for elements that was not found. It is a valid value, but it is impossible to create container with such max index. If std::vector has size equal to std::numeric_limits<size_t>::max(), then maximum allowed index will be (std::numeric_limits<size_t>::max()-1), since elements counted from 0.
std::vector has random-access iterators. You can do pointer arithmetic with them. In particular, this my_vec.begin() + my_vec.size() == my_vec.end() always holds. So you could do
const vector<type>::const_iterator pos = std::find_if( firstVector.begin()
, firstVector.end()
, some_predicate(parameter) );
if( position != firstVector.end() ) {
const vector<type>::size_type idx = pos-firstVector.begin();
doAction( secondVector[idx] );
}
As an alternative, there's always std::numeric_limits<vector<type>::size_type>::max() to be used as an invalid value.
In this case, it is safe to cast away the unsigned portion unless your vector can get REALLY big.
I would pull out the where.size() to a local variable since it won't change during the call. Something like this:
int find( const vector<type>& where, int searchParameter ){
int size = static_cast<int>(where.size());
for( int i = 0; i < size; i++ ) {
if( conditionMet( where[i], searchParameter ) ) {
return i;
}
}
return -1;
}
If a vector has N elements, there are N+1 possible answers for find. std::find and std::find_if return an iterator to the found element OR end() if no element is found. To change the code as little as possible, your find function should return the equivalent position:
size_t find( const vector<type>& where, int searchParameter )
{
for( size_t i = 0; i < where.size(); i++ ) {
if( conditionMet( where[i], searchParameter ) ) {
return i;
}
}
return where.size();
}
// caller:
const int position = find( firstVector, parameter );
if( position != secondVector.size() ) {
doAction( secondVector[position] );
}
I would still use std::find_if, though.
Something like this, I think. find_if_counted.hpp:
#ifndef FIND_IF_COUNTED_HPP
#define FIND_IF_COUNTED_HPP
#include <algorithm>
namespace find_if_counted_impl
{
template <typename Func>
struct func_counter
{
explicit func_counter(Func& func, unsigned &count) :
_func(func),
_count(count)
{
}
template <typename T>
bool operator()(const T& t)
{
++_count;
return _func(t);
}
private:
Func& _func;
unsigned& _count;
};
}
// generic find_if_counted,
// returns the index of the found element, otherwise returns find_if_not_found
const size_t find_if_not_found = static_cast<size_t>(-1);
template <typename InputIterator, typename Func>
size_t find_if_counted(InputIterator start, InputIterator finish, Func func)
{
unsigned count = 0;
find_if_counted_impl::func_counter<Func> f(func, count);
InputIterator result = find_if(start, finish, f);
if (result == finish)
{
return find_if_not_found;
}
else
{
return count - 1;
}
}
#endif
Example:
#include "find_if_counted.hpp"
#include <cstdlib>
#include <iostream>
#include <vector>
typedef std::vector<int> container;
int rand_number(void)
{
return rand() % 20;
}
bool is_even(int i)
{
return i % 2 == 0;
}
int main(void)
{
container vec1(10);
container vec2(10);
std::generate(vec1.begin(), vec1.end(), rand_number);
std::generate(vec2.begin(), vec2.end(), rand_number);
unsigned index = find_if_counted(vec1.begin(), vec1.end(), is_even);
if (index == find_if_not_found)
{
std::cout << "vec1 has no even numbers." << std::endl;
}
else
{
std::cout << "vec1 had an even number at index: " << index <<
" vec2's corresponding number is: " << vec2[index] << std::endl;
}
}
Though I feel like I'm doing something silly... :X Any corrections are welcome, of course.
You probably should not use your own function here.
Use find() from STL.
Example:
list L;
L.push_back(3);
L.push_back(1);
L.push_back(7);
list::iterator result = find(L.begin(), L.end(), 7);
assert(result == L.end() || *result == 7);
Take a vector of integer and a key (that we find in vector )....Now we are traversing the vector until found the key value or last index(otherwise).....If we found key then print the position , otherwise print "-1".
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int>str;
int flag,temp key, ,len,num;
flag=0;
cin>>len;
for(int i=1; i<=len; i++)
{
cin>>key;
v.push_back(key);
}
cin>>num;
for(int i=1; i<=len; i++)
{
if(str[i]==num)
{
flag++;
temp=i-1;
break;
}
}
if(flag!=0) cout<<temp<<endl;
else cout<<"-1"<<endl;
str.clear();
return 0;
}
Get rid of the notion of vector entirely
template< typename IT, typename VT>
int index_of(IT begin, IT end, const VT& val)
{
int index = 0;
for (; begin != end; ++begin)
{
if (*begin == val) return index;
}
return -1;
}
This will allow you more flexibility and let you use constructs like
int squid[] = {5,2,7,4,1,6,3,0};
int sponge[] = {4,2,4,2,4,6,2,6};
int squidlen = sizeof(squid)/sizeof(squid[0]);
int position = index_of(&squid[0], &squid[squidlen], 3);
if (position >= 0) { std::cout << sponge[position] << std::endl; }
You could also search any other container sequentially as well.