C++ Vector Elements Count - c++

In C++, using the vector header, how do I find the number of elements?
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
system("pause");
return 0;
primer(1000);
}
int primer(int max){
vector<int> a;
a[1]=2;
for (int i=2;i<=max;i++){
bool prime=true;
for (int ii=1;ii<=#a;ii++) {
if i/a[ii]==math.floor(i/a[ii]) {
prime=false;
}
}
if prime==true {
a[#a+1]=i;
}
}
for (i=1;i<=#a;i++) {
cout << a[i]);
}
}
}
I originally wrote the code
for lua, and this is my attempt to translate it to C++. I would appreciate specifics, for example, a specific replacement for a bad line. I tried to replace #a with a.size, but it didn't work.
Revised:
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int primer(int max);
int main()
{
primer(5);
system("pause");
return 0;
}
int primer(int max){
vector<int> a;
a[1]=2;
for (int i=2;i<=max;i++){
bool prime=true;
for (int ii=0;ii<a.size();ii++) {
if (i/a[ii]==floor(i/a[ii])) {
prime=false;
}
}
if (prime==true) {
a.push_back(i);
}
}
for (int iii=0;iii<=a.size();iii++) {
cout << a[iii] << endl;
}
}
It crashes without running. For what reason is this?

a.size().
I would recommend using some sort of reference material, e.g. http://cplusplus.com/reference/stl/vector/.

To answer your immediate question:
a.size(); // use size as a function
But there are several other things wrong with your code:
vector<int> a;
a[1]=2;
Ordinarily you need to set the size of a beforehand, since C++ must allocate space for it. You can use push_back() though, which will incrementally add space as needed.
Also, C++ arrays start counting at 0:
for (int ii=1;ii<=#a;ii++) {
This should be
ii = 0
And since arrays start at 0, they end at size() - 1, not size().

for( int ii = 0; ii < a.size(); ++ii )
C and C++ array indexes start at zero and end at size-1, so you need to compare less-than, not less-than-or-equal-to. vector follows the same rule.

Another obvious problem that needs pointing out:
int main()
{
system("pause");
return 0;
primer(1000);
}
Your function is never going to be called. Your app will exit when main returns.

a[#a+1]=i;
changed to use size() becomes:
a[ a.size() + 1 ] = i;
This is syntactically correct but guaranteed wrong. It should be:
a.push_back(i);
Read the API referenced by Oli.

Related

How can I eliminate garbage value in this output?

In this below program, I'm trying to marge 2 arrays into a single vector, but while returning the function I'm getting additional garbage values along with it.
Please anyone suggest me how to remove those!
#include <bits/stdc++.h>
#include <vector>
#include <string>
using namespace std;
vector <int> merge(int a[],int b[]){
vector <int> marr1;
marr1.clear();
int i=0,j=0;
while(i+j <= ((*(&a+1)-a)+(*(&b+1)-b)))
{
if ((i<= *(&a+1)-a)){
marr1.push_back(a[i]);
i++;
}
else{
marr1.push_back(b[j]);
j++;
}
}
sort(marr1.begin(),marr1.end());
return marr1;
}
int main(){
//array imlementation
int arr1[] = {5,7,4,5},arr2[] = {8,3,7,1,9};
vector <int> ans;
ans.clear();
ans = merge(arr1,arr2);
for (auto i=ans.begin();i<ans.end();++i){
cout<<*i<<"\t";
}
}
output produced:
0 0 0 0 1 3 4 5 5 7 7 8 9 32614 32766 4207952 1400400592
You want something like this:
include <iostream>
#include <vector>
#include <algorithm> // <<<< dont use #include <bits/stdc++.h>,
// but include the standard headers
using namespace std;
vector <int> mergeandsort(int a[], int lengtha, int b[], int lengthb) { // <<<< pass the lengths of the arrays
vector <int> marr1; // <<<< and use meaningful names
// marr1.clear(); <<<< not needed
for (int i = 0; i < lengtha; i++)
{
marr1.push_back(a[i]);
}
for (int i = 0; i < lengthb; i++)
{
marr1.push_back(b[i]);
}
sort(marr1.begin(), marr1.end());
return marr1;
}
int main() {
int arr1[] = { 5,7,4,5 }, arr2[] = { 8,3,7,1,9 };
vector <int> ans;
// ans.clear(); <<<< not needed
ans = mergeandsort(arr1, 4, arr2, 5);
for (auto i = ans.begin(); i < ans.end(); ++i) {
cout << *i << "\t";
}
}
Look at the <<<< comments for explanations.
There is still room for improvement:
passing the hard coded lengths of the arrays in mergeandsort(arr1, 4, arr2, 5) is bad practice, if you add/remove element from the arrays, you need to change the lengths too.
you shouldn't use raw arrays in the first place but vectors like in vector<int> arr1[] = { 5,7,4,5 };, then you don't need to care about the sizes as a vectors knows it's own size. I leave this as an exercise for you.
Since you're not passing the length of the array, there is no way inside the merge function to know about their length. Your program seems to produce undefined behavior as can be seen here. If you execute this program again and again you'll notice that the output changes which is an indication of undefined behavior.
Secondly, you're using std::vector::clear when there is no need to use it in your program. I have commented it in the code example i have given below.
You can use pass the length of the arrays as arguments to the merge function. Below is the complete working example:
#include <bits/stdc++.h>
#include <vector>
#include <string>
using namespace std;
vector<int> merge(int a[], int lengthA, int b[], int lengthB){
vector <int> marr1;
//marr1.clear();//no need for this since the vector is empty at this point
for(int i = 0; i< lengthA; ++i)
{
//std::cout<<"adding: "<<a[i]<<std::endl;
marr1.push_back(a[i]);
}
for(int i = 0; i< lengthB; ++i)
{
//std::cout<<"adding: "<<b[i]<<std::endl;
marr1.push_back(b[i]);
}
sort(marr1.begin(),marr1.end());
return marr1;
}
int main(){
//array imlementation
int arr1[] = {5,7,4,5},arr2[] = {8,3,7,1,9};
vector <int> ans;
//ans.clear();//no need for this since the vector is empty at this point
ans = merge(arr1,4, arr2, 5);
for (auto i=ans.begin();i<ans.end();++i){
cout<<*i<<"\t";
}
}
You pass two int[] which degrade to pointers. This means you cannot tell the number of elements which you attempt to do with i+j <= ((*(&a+1)-a)+(*(&b+1)-b)). Either pass in a length of each array, or even better (C++) pass in two vectors instead. Also, if you don't know the STL has a merge() function in <algorithm>.

How to insert the range of numbers to an array by iterating through it?

I am making a program, in which I need to iterate the numbers, starting from 1 to num then put the value of that array {1...num} to a variable that can be called in the for loop.
This is where I am at.
int main()
{
int num = 0;
cin >> num;
for (int i = 1; i <= num; i++)
{
procnum[i];
}
}
I need procnum[num] to have a value like ...
int procnum[num] = {1,2,3...num};
If you can use std::vector and std::iota, this is just two line code.
No need to for(index) loop the array. See live example here
#include <vector> // std::vector
#include <numeric> // std::iota
std::vector<int> procnum(some_size);
std::iota(procnum.begin(), procnum.end(), 1);
In C++11, no need to even write a loop, unless you need to do error checking (e.g. check that reading input succeeded, or that the input value is valid).
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
int main()
{
int size;
std::cin >> size;
std::vector<int> procnum(size);
std::iota(procnum.begin(), procnum.end(), 1); // starting value is 1
// output vector to demonstrate it is populated
std::copy(procnum.begin(), procnum.end(), std::ostream_iterator<int>(std::cout," ");
std::cout << "\n";
}
Before C++11, there was no algorithm std::iota(), but it is possible to use std::generate() and a simple functor to achieve the same effect.
you can use std::vector to create dynamic arrays:
#include <iostream>
#include <vector>
int main() {
int size;
std::cin >> size;
std::vector<int> procnum(size);
for (int i = 0; i < size; ++i) {
procnum[i] = i + 1;
}
}
you shouldn't use namespace std; - read here why.

Recursive function, which writes integer digits in an array(vector) in C++?

I have a C++ program, in which I have to create a recursive function that writes all the digits of a given positive integer in an array - in this case a vector.
However, when I compile the program and enter a number, it stops working. I want to ask why this happens?
#include <iostream>
#include <vector>
using namespace std;
vector <int> arr;
int temp;
int fill_Array(int num)
{
if(num>=1 && num<=9)
{
arr.push_back(num);
}
temp = fill_Array(num)%10;
arr.push_back(temp);
num/=10;
}
int main()
{
int n;
cin>>n;
fill_Array(n);
for(int i=0; i<arr.size(); i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
In the given code, recursion function does not returning any value, so return type for that function have no use.
calling the function for recursion is in the wrong place. Correct code given below:
#include <iostream>
#include <vector>
using namespace std;
vector <int> arr;
int temp;
void fill_Array(int num)
{
if(num>=1 && num<=9)
{
arr.push_back(num);
}
else{
temp = num%10;
arr.push_back(temp);
fill_Array(num/=10);
}
}
int main()
{
int n;
cin>>n;
fill_Array(n);
for(int i=0; i<arr.size(); i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
A couple of reasons I can see:
There is no conditional to stop the recusion so it will keep going until it runs out of stack or memory. I presume you want to stop when num is zero
fill_Array has no return value so will assign temp with some random value which will be pushed into the array
Also why use recursion for this when iterative would be easier and more obvious what it is doing

How to use a void() function to print a vector in c++?

I have a function which calculates the squares of the numbers from 1 - 100. I would like to use another function to print the results. I would like to know how to make a function like that not only works with vectors but with any type.
Here's what i have so far:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
using namespace std;
vector<double> Sqrs(int val, double sqr, vector<double> result){
for(val = 1;val < 100;val++){
sqr = sqrt(val);
result.push_back(sqr);
}
return result;
}
void Print(int val, vector<double> result){
for(unsigned int i = 0;i < result.size();i++){
cout << val << setw(10);
cout << &result << endl;
}
}
int main()
{
Print();
return 0;
}
The problem is that it says I have too few arguments on Print();. I dont know what arguments to put because when I put the val, result, or with int val, vector<double>result, it gives me a lot of errors. I just don't know how to make a separate function to print something I have used in another function other than main.
EDIT: It seems that i have asked the question stupidly. I would like to know for example i have a function that calculates 2 numbers named int val (int a, int b) and that function returns a value "c". So now i would like to make another function named Print and use the returned value from the other function val so i can print it. Then in the main function i would just call the Print() function.
A brief translation to English of your program at the highest level is:
Here are the libraries I want to use.
This is what I mean if I ever ask you to do Sqrs with an int, a double, and a vector<double>
This is what I mean if I ever ask you to do Print with an int and a vector<double>
and finally the thing you actually tell the program to do is
Print with nothing
Output 0
So as you can see, this code doesn't really seem to resemble any of the things you describe. Before you worry about trying to write very general code, you should work on trying to get a special case right first.
#include <iostream>
#include <cmath>
#include <iomanip>
#include <vector>
using namespace std;
vector<double> myFunc(int x, vector<double> &vec){
double rez = 0.0;
for(int i = 0;i < 100;i++){
rez = sqrt(x);
vec.push_back(rez);
x++;
}
return vec;
}
void Print(vector<double> &vec){
for(int i = 0;i != vec.size();i++){
cout << vec[i] << endl;
}
}
int main()
{
vector<double> vec1;
myFunc(1, vec1);
Print(vec1);
return 0;
}
This is what i wanted to do.

Code failure insert digits before data of the vector

I am supossed to do a code using function which after asking the user for input,puts number before the vector like this:
if vector is 11,12,13,14
new vector is 1 11 2 12 3 13 4 14 until the vector finishes and then I have to print it but I get an error of vector subscript out of range,aprecciate any help.
Here is my code
#include<iostream>
#include<string>
#include<vector>
using namespace std;
vector<double> llena_vector(int x,vector<double> ingreso)
{
cout<<"Ingrese numeros: ";
while(cin>>x);
ingreso.push_back(x);
return ingreso;
}
vector<double> arma_vector(int contador,vector<double> intercalado)
{
int i=0;
for(contador=1;contador< intercalado.size()+1;contador++);{
intercalado.insert(intercalado.begin()+i,contador);i++;}
return intercalado;
}
vector<double> imprime_vector(int cuenta,vector<double> imprimir)
{
for(cuenta=0;cuenta<imprimir.size();cuenta++);
cout<<imprimir[cuenta]<<" ";
return imprimir;
}
int main()
{
int y=0;
int q=0;
int w=0;
int f=0;
vector<double> usuario;
vector<double> guardar;
vector<double> resultado;
vector<double> print;
guardar= llena_vector(y,usuario);
resultado=arma_vector(q,guardar);
print=imprime_vector(w,resultado);
system("pause");
}
Here is a cleaner version of the code, in working condition.
#include <iostream>
#include <vector>
using namespace std;
void fill_vector(vector<double>& v)
{
cout << "Enter 5 numbers." << endl;
for (int i = 0; i < 5; ++i)
{
double d;
cin >> d;
v.push_back(d);
}
}
void insert_count(vector<double>& v)
{
size_t size = v.size();
for (size_t i = 0, j = 0; i < size; ++i, j += 2)
{
vector<double>::iterator pos = v.begin() + j;
v.insert(pos, i + 1);
}
}
void print_vector(vector<double>& v)
{
for (size_t i = 0; i < v.size(); ++i)
cout << v[i] << " ";
cout << endl;
}
int main()
{
vector<double> v;
fill_vector(v);
insert_count(v);
print_vector(v);
}
Like others (may have) pointed out:
you didn't need to pass by value (you're basically passing around a bunch of copies), you can pass by reference instead to reduce overhead and speed it up
you shouldn't put semicolons (;) directly behind your loop statements
size_t is often better than int when looping on size
you included <string> when it wasn't being used
you were passing arguments that weren't needed (e.g. a counter)
you used a while loop for user input, but it's only appropriate when piping in data otherwise it will loop forever; a for loop with a known count is more appropriate for user input
the function that inserted numbers between the existing elements had an error, you were incorrectly calculating the position to insert
your code formatting was a mess, making the code very difficult to read
you shouldn't pollute the namespace (i.e. using namespace std), but I left it as is since it's common in example code
if you're using C++11, I recommend using a for-each loop for printing the vector, and the auto keyword when declaring the iterator
i guess there is a typo: you should remove the last ; in for(cuenta=0;cuenta<imprimir.size();cuenta++);
Edit: as pointed by jrd1, you have this typo in all your for and while loops...
To begin with, your code has a number of issues. But, I've modified it to keep it as similar to your original.
#include <iostream>
#include <string>
#include <deque>
#include <cstdlib>
using namespace std;
deque<double> llena_deque(int x, deque<double> ingreso)
{
cout<<"Ingrese numeros: ";
while(cin>>x)
ingreso.push_back(x);
return ingreso;
}
deque<double> arma_deque(int contador, deque<double> intercalado)
{
int size = intercalado.size()+1;
for(int i=1; i < size; ++i) {
cout << i << endl;
intercalado.push_front(i);
}
return intercalado;
}
deque<double> imprime_deque(int cuenta, deque<double> imprimir)
{
for(cuenta=0;cuenta<imprimir.size();cuenta++)
cout << imprimir[cuenta] << " ";
return imprimir;
}
int main()
{
int y=0;
int q=0;
int w=0;
int f=0;
deque<double> usuario;
deque<double> guardar;
deque<double> resultado;
deque<double> print;
guardar= llena_deque(y,usuario);
resultado=arma_deque(q,guardar);
print=imprime_deque(w,resultado);
return 0;
}
All your loops had ; at the end of them. That's one reason why you're getting your errors, as the semi-colon terminates a statement - hence, your loops were never truly accessing the vectors, which is why you were getting the memory access violations.
You're passing all your memory by value (which could potentially be slow). Consider using references.
Your operations suggest that you constantly need to keep pushing new data in front of your vector. If so, then use deque (as I did) as it is has functionality designed explicitly for that purpose (insert operations at both ends).
Although, I will say that the logic of your code is quite puzzling at times: i.e. in arma_vector, why pass the value of contador if you don't even use it? You could have used i instead...