Coming from a syntactically simpler, dynamically typed language with a lot more built in functions (you know the one), I wanted to teach myself C++. So I wanted to try recreating the zip(a,b) function. The idea is to take two list-like objects, and return a list of pairs from those two objects. E.g. zip({1,2,3},{a,b,c}) should return {{a,1}, {b,2}, {c,3}}.
Now I gather that the way to make such objects in C++ is with vectors, rather than arrays? Below is my attempt to code the function, and a test to print its contents, but I get no actual output in the console. I even tried two different methods for printing the vector, so I suppose my zip() function messed up.
#include <vector>
#include <iostream>
#include <string>
std::vector<std::vector<float>> zip(std::vector<float> a, std::vector<float> b)
{
//Returns a vector of size 2 vectors for tuples of <a_i, b_i>
//if the vectors are not of equal size, truncates to shortest.
int len_a = a.size();
int len_b = b.size();
int size;
if (len_a<len_b)
{
size=len_a;
}
else
{
size=len_b;
}
std::vector<std::vector<float>> c;
for (int i; i<=size; i++)
{
//c[i] = {a[i],b[i]}; commented out. I think the below is more correct?
c.push_back( {a[i] , b[i]} );
}
return c;
}
int main(){
std::vector<float> sample_a = {1,2,3,4,5};
std::vector<float> sample_b= {7,7,7};
std::vector<std::vector<float>> output_c;
output_c = zip(sample_a,sample_b);
//First attempted method for print
for (std::vector<float> a: output_c)
{
for (float b: a)
{
std::cout << b << std::endl;
}
}
//Second attempted method for print
for (int i=0; i<=output_c.size();i++)
{
for (int j=0; j<=output_c[i].size(); j++)
{
std::cout << output_c[i][j];
}
}
return 0;
}
I'm still very new to the use of C++, and my 'learning' strategy has been to write smallish programs for things I found useful. Any general tips on improving the above also much appreciated!