Code failure insert digits before data of the vector - c++

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...

Related

Unexpected value while placeing integers into an array

I am trying to fill an array with different integers, but it doesn't work as expected.
#include <iostream>
using namespace std;
int main(){
int i=0;
int num;
int MyArray[]={};
while (true) {
cout<<"sayi giriniz"<<endl;
cin>>num;
MyArray[i]=num;
i++;
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
}
return 0;
}
https://imgur.com/a/tANGpSY
When I enter the 3rd value it gives an unexpected result.
int MyArray[]={};
Now, MyArray has a size of 0, so any indexes that you tried to access MyArray will cause undefined behavior.
If you want to make an array that is dynamically in size, use std::vector in the <vector> header.
Change
int MyArray[]={};
to
std::vector<int> MyArray;
This:
MyArray[i]=num;
i++;
To this:
MyArray.push_back(num); // you don't even need i
This
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
To this:
for(const auto &i : MyArray) // range based for loop, recommend
{
std::cout << i << '\n';
}
Also, using namespace std; is bad, so don't use it.
If you want to take input and are unsure about the number of elements, you should use a vector. The array which you have made is of 0 size. It will surely give you an error.

Vector push back function in structure not working

I want to store a vector in a structure and then append to the vector from a function. Does this even make sense or can I only create elements in my vector when creating it? If no, where is the error in the code below, because if I execute it, it simply prints nothing. I want it to store the numbers 0-4 as components of the vector nums in holder.
#include "iostream"
#include "vector"
using namespace std;
struct layers{
vector<float> nums;
};
void range(layers layer){
for(int n = 0; n< 5; n++){
layer.nums.push_back(n);
}
}
int main(){
layers holder;
range(holder);
for(int k = 0; k < holder.nums.size(); k++){
std::cout << holder.nums[k] << " ";
}
return 0;
}
You have to pass the layer parameter by reference, not by value. Instead of void range(layers layer), do void range(layers &layer).
If you pass by value, you are making a copy of the vector and then modify this copy inside the function, so your original vector remains untouched. If you pass by reference, the original vector is modified.
Try it online!
#include "iostream"
#include "vector"
using namespace std;
struct layers{
vector<float> nums;
};
void range(layers & layer){
for(int n = 0; n< 5; n++){
layer.nums.push_back(n);
}
}
int main(){
layers holder;
range(holder);
for(int k = 0; k < holder.nums.size(); k++){
std::cout << holder.nums[k] << " ";
}
return 0;
}
Output:
0 1 2 3 4

How can I print the numbers in main function?

I am new to c++ language. I am trying to solve a problem using function. I have to print the pentagon numbers untill the integer input, but when function returns the values, it only prints one value. I would love some help with it.
#include<iostream>
using namespace std;
int pent(int num){
int p;
for(int i=1;i<=num;i++){
p=(i*(3*i-1)/2);
}
return p;
}
int main(){
int num;
cin>>num;
int sender=pent(num);
cout<<sender<<endl;
return 0;
}
Your function returns int, that is a single integer. To return more, you can use std::vector. As you probably are not familiar with it, I will give you some pointers...
The most simple constructor creates a vector with no entries:
std::vector<int> x;
You can reserve space for elements via reserve:
x.reserve(num);
The vector still has no elements, but it already allocated enough space to hold num elements. This is important, because when we will add elements the vector will grow and that potentially requires to copy all elements to a different place in memory. We can avoid such frequent reallocations by reserving enough space upfront.
To add elements to the vector you can use push_back:
x.push_back(42);
Eventually to print all elements of the vector we can use a range-based for loop:
for (auto element : x) std::cout << element << " ";
So you can rewrite your code like this:
#include <iostream>
#include <vector>
std::vector<int> pent(int num){
std::vector<int> result;
result.reserve(num);
for(int i=1;i<=num;i++){
result.push_back(i*(3*i-1)/2);
}
return result;
}
int main(){
int num;
std::cin >> num;
auto sender = pent(num);
for (auto number : sender) std::cout << number << " ";
}
In your program, from your pent() function you are only returning last calculated value. In you ever time, you are overwriting you variable p.
So there is a way which #asmmo is suggesting, to print in pent() function.
Or you can pass a vector to your pent() function and store values in that and print it in main function.
For your ref:
void pent(int num, vector<int> &arr) {
int p;
for (int i = 1; i <= num; i++) {
arr[i-1] = (i*(3 * i - 1) / 2);
}
}
int main() {
int num;
cin >> num;
vector<int> arr(num);
pent(num, arr);
for (int i = 0; i < num; i++) {
cout << arr[i] << endl;
}
return 0;
}

Finding minimum and maximum in a array c++

I have to find the minimum and maximum value of elements in a array using divide and conquer. I have written a code but it is not working for more then 6 elements in array. I don't know whats the problem
#include<iostream>
using namespace std;
int minimum=999,maximum,mi,ma;
void result(int mi,int ma)
{
if(maximum<ma)
{
maximum=ma;
}
if(minimum>mi)
{
minimum=mi;
}
}
void maxmin(int arr[],int i,int j)
{
cout<<" i ="<<i<<" j= "<<j<<endl;
if(i==j)
{
mi=ma=arr[i];
result(mi,ma);
}
else if(i==j-1)
{
if(arr[i]>arr[j])
{
ma=arr[i];
mi=arr[j];
}
else
{
mi=arr[i];
ma=arr[j];
}
result(mi,ma);
}
else
{
int mid=i+j/2;
maxmin(arr,i,mid);
maxmin(arr,mid+1,j);
}
}
int main()
{
int arr[10],n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
maxmin(arr,0,n-1);
cout<<" max "<<maximum<<" min "<<minimum<<endl;
return 0;
}
Your code has a few mistakes
Your code reads n from the user input, but you provided only 10 sized array, and user can try to input 10+ numbers, so we will have an undefined behavior in that case.
You write it very bad and unreadable. If you want somebody else to read your code, check in the your favourite book or in the internet information about how to write beautiful and readable code.
You implemented that algorithm yourself. It is a bad habit, use the standard library algorithms and you will not encounter such mistake.
.
#include <iostream> // std::cin, std::cout
#include <cstddef> // std::size_t
#include <algorithm> // std::min_element, std::max_element
int main ()
{
std::size_t array_size;
std::cin >> array_size;
int *some_array = new int[array_size]; // Allocate memory dynamically
for(std::size_t i = 0; i < array_size; ++i)
{
std::cin >> some_array[i];
}
/* Standard library operate on iterators, they are special classes
* that have interface that is similar in many cases to pointers (so we can use pointers as iterators).
* std::min/max_element needs one iterator for the sequence beginning
* and one iterator after the end. It returns iterator to a found element.
*/
int min = *std::min_element(some_array, some_array + array_size);
int max = *std::max_element(some_array, some_array + array_size);
delete[] some_array;
std::cout << "Min = " << min << std::endl << "Max = " << max;
std::cout << std::endl;
}
Code isn't well written and first dry run your code, you will find the problem easily.
Change
else
{
int mid=i+j/2;
maxmin(arr,i,mid);
maxmin(arr,mid+1,j);
}
To
else
{
int mid=(i+j)/2; /*** Adding brackets ***/
maxmin(arr,i,mid);
maxmin(arr,mid+1,j);
}
And check the logic for calling the result function (because according to your logic the two subsets are individually calculating MIN and MAX in itself not in whole array)

C++ Program Apparently Printing Memory Address instead of Array

#include <iostream>
using namespace std;
int main(){
int findMax(int *);
const int MAX = 100;
int values[MAX];
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
char *helper;
// Clean input array and transfer it to values.
for(int i = 0; i < (MAX) && ivals[i] != 0; i++){
helper = ivals[i * 2];
values[i] = atoi(helper);
}
int mval = findMax(values);
cout << values << endl << mval;
return 0;
}
//Function to find the maximum value in the array
int findMax(int arr[]){
int localmax = 0;
for(int i = 0; i < (sizeof(arr)/sizeof(int)); i++){
if(arr[i] > localmax){
localmax = arr[i];
}
}
return localmax;
}
The purpose of this program is for the user to input a space-separated series of values ended by a 0. That array is then to be analyzed to find the max. I figured out how to convert what is originally a char[] into an int[] so that I can use the findMax() function on it without error but the sorting loop seems to have a problem of its own and when "cout << values << endl << mval;" is called, it returns only a memory address instead of what should be a non-spaced sequence of ints. Can anybody explain what I am doing wrong? It seems that I may have made some mistake using the pointers but I cannot figure out what.
Printing values won't print the contents of the array as you expect, it will print the memory location of the first element of the array.
Try something like this instead:
#include <iterator>
#include <algorithm>
// ...
copy(&values[0], &values[MAX], ostream_iterator(cout, " "));
Sorry I can't post actual working code, but your original post is a mess with many syntax and syntactic errors.
EDIT: In the interest of being more complete and more approachable & understandable to beginners, I've written a small program that illustrates 4 ways to accomplish this.
Method 1 uses copy with an ostream_iterator as I've done above.
Method 2 below is probably the most basic & easiest to understand.
Method 3 is a C++0x method. I know the question is tagged C++, but I thought it might be educational to add this.
Method 4 is a C++ approach using a vector and for_each. I've implemented a functor that does the dumping.
Share & Enjoy
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
struct dump_val : public unary_function<int,void>
{
void operator()(int val)
{
cout << val << " ";
}
};
int main(){
int vals[5] = {1,2,3,4,5};
// version 1, using std::copy and ostream_iterator
copy(&vals[0], &vals[5], ostream_iterator<int>(cout, " "));
cout << endl;
// version 2, using a simple hand-written loop
for( size_t i = 0; i < 5; ++i )
cout << vals[i] << " ";
cout << endl;
// version 3, using C++0x lambdas
for_each(&vals[0], &vals[5], [](int val)
{
cout << val << " ";
}
);
cout << endl;
// version 4, with elements in a vector and calling a functor from for_each
vector<int> vals_vec;
vals_vec.push_back(1);
vals_vec.push_back(2);
vals_vec.push_back(3);
vals_vec.push_back(4);
vals_vec.push_back(5);
for_each( vals_vec.begin(), vals_vec.end(), dump_val() );
cout << endl;
}
When you pass around an array of X it's really a pointer to an array of X that you're passing around. So when you pass values to cout it only has the pointer to print out.
You really should look into using some of the standard algorithms to make your life simpler.
For example to print all the elements in an array you can just write
std::copy(values, values+MAX, std::ostream_iterator<int>(std::cout, "\n"));
To find the max element you could just write
int mval = *std::max_element(values, values+MAX);
So your code becomes
#include <iostream>
using namespace std;
int main(){
const int MAX = 100;
int values[MAX];
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
char *helper;
// Clean input array and transfer it to values.
for(int i = 0; i < (MAX) && ivals[i] != 0; i++){
helper = ivals[i * 2];
values[i] = atoi(helper);
}
copy(values, values+MAX, ostream_iterator<int>(cout, "\n"));
cout << *std::max_element(values, values+MAX);
return 0;
}
Doing this removes the need for your findMax method altogether.
I'd also re-write your code so that you use a vector instead of an array. This makes your code even shorter. And you can use stringstream to convert strings to numbers.
Something like this should work and is a lot less code than the original.
int main(){
vector<int> values;
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
int temp = 0;
stringstream ss(ivals);
//read the next int out of the stream and put it in temp
while(ss >> temp) {
//add temp to the vector of ints
values.push_back(temp);
}
copy(values.begin(), values.end(), ostream_iterator<int>(cout, "\n"));
cout << *std::max_element(values.begin(), values.end());
return 0;
}
Array of int is promoted to a pointer to int when passed to a function. There is no operator << taking ordinary array. If you want to use operator << this way, you need to use std::vector instead.
Note: it is possible technically to distinguish array when passed to a function using template, but this is not implemented for standard operator <<.
for(int i = 0; i < (sizeof(arr)/sizeof(int)); i++){
sizeof(arr) here is the size of the pointer to the array. C++ will not pass the actual array, that would be grossly inefficient. You'd typically only get one pass through the loop. Declare your function like this:
int findMax(int* arr, size_t elements) {
//...
}
But, really, use a vector.
Oh, hang on, the question. Loop through the array and print each individual element.