Switching data from array to vector - c++

I'm trying to convert my array to a vector, yet I'm having trouble printing it.
It says in int main() in my for loop that v is undefined. When I define
vector v; inside int main() the program compiles and runs and yet prints nothing. What am I doing wrong?
#include <iostream>
#include <vector>
using namespace std;
vector<int> a2v(int x[], int n)
{
vector<int> v(n);
for(int i = 0; i < n; i++)
{
v.push_back(x[i]);
}
return(v);
}
int main()
{
vector<int> a2v(int x[], int n);
int array[] = {11,12,13,14,15,16,17,18};
a2v(array, 8);
for(int i = 0; i < v.size(); i++)
{
cout << v[i] <<" ";
}
cout << endl;
return(0);
}

This is your program corrected:
#include <iostream>
#include <vector>
using namespace std;
vector<int> a2v(int x[], int n)
{
vector<int> v(0);
v.reserve(n); //optional
for(int i = 0; i < n; i++)
{
v.push_back(x[i]);
}
return(v);
}
int main()
{
int array[] = {11,12,13,14,15,16,17,18};
auto v = a2v(array, 8);
for(size_t i = 0; i < v.size(); i++)
{
cout << v[i] <<" ";
}
cout << endl;
return(0);
}
There were 2 errors:
In the function a2v, you instantiated a vector of 0 with length n, and then you pushed back other elements;
You were not defining v inside the main, as the return value of a2v

The vector you want to read is the return of the a2v function.
But there is a lot more simpler than that to go from C-array to vector array , I put here the example in found the vector reference web page :
http://www.cplusplus.com/reference/vector/vector/vector/
int myints[] = {16,2,77,29};
std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

When you define a variable, such as your vector v, you always do it in a certain scope. The body of a function such as a2v, or main, is an example of a possible scope. So if you only do it in the function a2v, that's the only scope where it will be visible.

It says in int main() in my for loop that v is undefined.
Well it will be because there is no v in main()
a2v(array, 8);
The above function call returns a vector so you need to collect the returned vector like
vector<int> v=a2v(array,8)
Also,
vector<int> v(n);//creates a vector of size n
for(int i = 0; i < n; i++)
{
v.push_back(x[i]);//adds n more elements to the vector
}
The returned vector has 2n elements and not n
Finally you could directly create a vector from an array as
vector<int> v(arr,arr+n);//where n is the number of elements in arr

Related

Select all elements but one with given index from std::vector?

Given a std::vector, for example of ints
std::vector vec{10, 20, 30}
how to select all items except of with given index, for example int i=1 resulting
std::vector {10, 30}?
If you just want to "select" values from the original vector, I would create another vector with all the new values.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vect{ 10, 20, 30 };
vector<int> selected;
int i = 1;
for (int j = 0; j < vect.size(); j++) {
if (j != i) {
selected.push_back(vect[j]);
}
}
// Added so you can check the new values
for (int z = 0; z < selected.size(); z++) {
cout << selected[z] << " ";
}
return 0;
}
However, if you want to erase values from your original vector I would recommend using the vector.erase method (research the documentation).
Here is a function for it where you can pass the vector and index and it will return you the new vector without that index element.
#include <iostream>
#include <vector>
using namespace std;
// returns a new vector without the v[index]
vector<int> getElementsExceptIndex(vector<int> v, int index){
vector<int> newVector;
for(auto &x:v ){
if(( &x - &v[0]) != index)
newVector.push_back(x);
}
return newVector;
}
int main() {
vector<int> originalVector{ 10, 20, 30 ,33,53};
int index=1;
auto RemovedIndexVector = getElementsExceptIndex(originalVector,index);
for(auto item:RemovedIndexVector)
cout<<item<<" ";
return 0;
}
// Output - 10 30 33 53
Hope this helps

Error : std:: out of range. where is out of range problem?

Given the following code :
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v;
v.emplace_back(1);
v.emplace_back(2);
for(int i = 2; i < n; i++){ // Is this problem point?
int data = v.at(i-1) + v.at(i-2);
v.emplace_back(data);
}
cout << v.at(n);
return 0;
}
this code has Error that is out of range.
I think that for loop has problem.
but I'm not sure where is out of range.
Is vector container index starting 0?
In each iteration of for(int i = 2; i < n; i++) you add one element to v. After the loop v contains max(2, n) elements.
The problem is caused by
cout << v.at(n);
with n >= 2. The last valid index is v.size() - 1. But to print the last value of a vector you can simply use:
cout << v.back();

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;
}

Remove all elements from array greater than n

I'm beginner in programming. Something is giving me trouble to code. Suppose, I've an array.
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
I want to remove all elements which are greater than 9. How can I do this?
You can do this if you use vector. First initialize vector with your array. Then use remove_if() function. Hope this will help.
#include <algorithm>
#include <vector>
int main()
{
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
vector<int> V(Array, Array+20);
vector<int> :: iterator it;
it = remove_if(V.begin(), V.end(), bind2nd(greater<int>(), 9));
V.erase (it, V.end()); // This is your required vector if you wish to use vector
}
You cannot remove items from an array, since they are fixed in size.
If you used std::vector, then the solution would look like this:
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
std::vector<int> Array = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
Array.erase(remove_if(Array.begin(), Array.end(), [](int n) { return n > 9; }),
Array.end());
copy(Array.begin(), Array.end(), ostream_iterator<int>(cout, " "));
}
Live example: http://ideone.com/UjdJ5h
If you want to stick with your array, but mark the items that are greater than 10, you can use the same algorithm std::remove_if.
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
int *overwrite_start = remove_if(std::begin(Array), std::end(Array), [](int n){ return n>9; });
fill(overwrite_start, std::end(Array), -1);
copy(std::begin(Array), std::end(Array), ostream_iterator<int>(cout, " "));
}
The above will move the "erased" items to the end of the array, and mark them with -1.
Live example: http://ideone.com/7rwaXy
Note the usage in both examples of the STL algorithm functions. The second example with the array uses the same remove_if algorithm function. The remove_if returns the start of the "erased" data, as remove_if doesn't actually remove, but moves the data to the end of the sequence.
i am try swap concept without using vector
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
int n;
int arr_len = sizeof(Array)/sizeof(int);
void print_array_value() {
int i;
cout << "\n";
for (i = 0; i < arr_len; i++) {
cout << Array[i] << ", ";
}
cout << " : " << arr_len << "\n";
}
void swap_array_value(int start) {
int i;
for ( ; (start+1) < arr_len; start++) {
Array[start] = Array[start+1];
}
}
void remove_array_value() {
int i;
for (i = 0; i < arr_len; i++) {
if (Array[i] > n) {
swap_array_value(i);
arr_len--;
i--;
}
}
}
void main () {
clrscr();
cout << "Enter the N value : ";
cin >> n;
print_array_value();
remove_array_value();
print_array_value();
cout << "Array Length : " << arr_len;
getch();
}