copy() copying all but last element from vector to array c++ - c++

I'm new to c++ and programming in general. Feel free to leave any hints, tips, or suggestions about my code!!
I am trying to copy my doubles from a vector to an array. I used copy() and it is copying all the elements except for the last. So the last element in the array stays exactly the same as it was before I used copy. So when I try to add the sums of the elements in the array, I don't get the correct sum.
Here is my code:
vector<double> myVector;
double myArray[4];
double myDouble = 0.0;
...//(add elements to vector)
copy(&myVector[0], &myVector[4], myArray);
for(int i = 0; i < 4; i++)
{
myDouble += myArray[i];
if(i == 4)
cout << "The sum of your values is " << fixed << setprecision(2) << myDouble << endl;
}
Thank you! Let me know if I need to be more specific.

The call to std::copy() copies four elements. This seems to fill your array. Note that your array contains exactly 4 elements and the last valid index is 3. Your vector myVector seems to include at least 5 elements: If it contains less then 5 elements, the expression myVector[4] is illegal. That said, the end iterator in a sequence always refers to the element behind the last value of the sequence, i.e., sequences are half-open: the begin is included, the end is the first element not included.
That said, you probably want to copy like this:
std::copy(myVector.begin(), std::min(4, myVector.size()) + myVector.begin(), myArray);
Of course, to get the sum of the elements in the vector you would actually use
double sum = std::accumulate(myVector.begin(), myVector.end(), 0.0);

Copy all elements from your vector this way:
copy(myVector.begin(), myVector.end(), myArray);

You have this code:
copy(&myVector[0], &myVector[4], myArray);
It copies 4 elements.
Now you have the decalaration of the destination array:
double myArray[4];
So the array has 4 elements.
It seems that you want to copy all but the last element, so copy just 3 elements:
copy(&myVector[0], &myVector[3], myArray);

Related

Multiplying and displaying the values of an array in C++

I am trying to complete a C++ exercise in which an array is displayed and the user is prompted to input a multiplier, which will result in the initial numbers that were displayed being multiplied by the user's input. Here is the code that I have so far:
#include <iostream>
using namespace std;
int main()
{
int array[5] = { 1, 2, 3, 4, 5 };
for (const auto& a : array)
{
std::cout << a << std::endl;
}
double multiplier;
cout << "Input a multiplier: ";
cin >> multiplier;
for (int array = 1; array <= 5; ++array)
{
array == multiplier * array;
std::cout << array << std::endl;
}
}
When it runs, it prints the correct array, with a newline being created after each array value, and prompts the user for the multiplier. However, when the multiplier is inputted, the values do not change. Here is an example output:
1
2
3
4
5
Input a multiplier: 2
1
2
3
4
5
The goal is to get this output:
1
2
3
4
5
Input a multiplier: 2
2
4
6
8
10
Any help or code improvement would be appreciated, as figuring out how to multiply and display the multiplied values is the only thing needed to be done in order to complete the exercise. Thank you in advance!
There are three big issues with your code:
1. Naming conventions.
Do not name your array and your temporary for loop variable the same thing. This will cause an issue further down the line, which I'll illustrate.
2. Incorrect operator
As minterm has mentioned, you are using a comparison operator instead of the equal operator. But that alone will not fix your issue.
3. Not accessing array values
You are not actually multiplying the array values with the multiplier. You have to access the elements, which means you cannot start the index at 1.
for (int i = 0; i < 5; i++){
array[i] *= multiplier
cout << array[i] << endl;
}
Use = instead of ==. Currently, it just evaluates a logical statement instead of setting it to a new value.
Also, you need to change "int array" in the for loop to a different name so as to not get it confused with the array called array. Call the variable in the for loop something else, like "int i".
So then the line in question would not be "array == multiplier*array", but instead something like "int j = multiplier * array[i]", and then have it print out j instead of array.
A simpler approach would be to use another range-based for loop instead of the indexed version:
for (auto& a : array)
{
a *= multiplier;
std::cout << a << std::endl;
}
If you don't need to update the array itself (after all, your code doesn't actually read from the array again), then you a very similar, though more straightforward version might be applicable:
for (const auto& a : array)
{
std::cout << a * multiplier << std::endl;
}
You have quite a few things going on that are incorrect.
First is your over scoping (maybe not the right term) the array value.
You have an array value declared outside of your for loop, and you're using the value array again inside of the for loop for the counter. So you're not actually doing anything to your array. You're actually trying to do something to the initialization variable.
Second you're using == instead of =
You're using a comparison operator (==) instead of an assignment operator (=), but there's other big no no's going on.
array is an int[5] not just an int
To actually modify each element of your array, you need to reference the index by saying array[index] where index is a value of 0 to length of array - 1, so 4 in your case.
You're using a double multiplier and trying to apply it to an int *
If you try to multiply by a double value like 2.5, your array values are going to be int's and not a number with a decimal value. You should make your int array [] into a double array []
Not accessing your array, starting from index 0
When looping through an array, the first index is always 0. You're using array = 1 and array <= 5. This would skip your first index, and give you an out of bound index at the end. You should use int index = 0; index < 5; index++; instead.
You're trying to print array
Since array is an int [] printing array in the for loop like that will just give you the address of where the array is. You'll have to either print out each index or use the enhanced for loop method after you've applied your multiplier.
If you're wanting to use your above implementation, do this
for (int index = 0; index < 5; index++)
{
array[index] *= multiplier; // Or you can use array[index] = multiplier * array[index]
std::cout << array[index] << std::endl;
}

How to remove the elements of an array within a certain range

I have a one-dimensional array of size 10. I want to remove the elements from 5 to 8. Can somebody give me an example of how to do it? This is how I defined my array but I have no idea about how to start.
#include <iostream>
#include <iomanip>
using namespace std;
int array[10] = {1,2,3,4,5,6,7,8,9,10};
So, the output should be 1,2,3,4,5,10. (index 0 = element 1)
Thanks
An alternative to arrays is to use a vector. In this case you can do:
#include <vector>
// create vector for integers
std::vector<int> v;
// set values from 1 to 10
for (int i=1; i<=10; i++)
v.push_back(i);
// erase from 5 to 8
v.erase (v.begin()+5, v.begin()+9);
BTW, if your compiler supports C++11, you can initialize your vector as:
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
In the above case, its an array of 10 elements array[10]. As the array size is fixed, it may not be possible to remove an item from the array.
Rather, you can assign null or someother value to the corresponding element.
BTW, I would rather use, std::list or std:: vector instead of array.
Anyhow, If you mean to get rid of that element, you'd need to shift all the ones to the right of that element one to the left:
for (int i = index; i < /* length */; i++)
array[index] = array[index+1];
array[length-1] = 0;
You can't literally remove them because C++'s built-in arrays (like C's) are fixed-size.
What you can do is overwrite them with the values that come after them, and then (if you want to) zero out the four now-extra positions at the end of the array. e.g.:
// copy latter values over the values we don't want
for (int i=4; i<6; i++) array[i] = array[i+4];
// zero out the no-longer-necessary values at the end, just so they won't appear valid anymore
for (int i=6; i<10; i++) array[i] = 0;
and then when printing the array, print only the first 6 values rather than all 10, since your array is (conceptually, even if not actually) "shorter" now.
Not sure what exactly you want your output to be, so I'm just providing another possible solution here:
// your input
int array[10] = {1,2,3,4,5,6,7,8,9,10};
// 1. put all invalid element in the back of the array
// "it" points to the first invalid element
int* it = std::remove_if(std::begin(array), std::end(array),
[](int e)
{
return (e >= 5) && (e <= 8);
});
// 2. then, mark them as -1 (from "it" to the last element)
std::transform(it, std::end(array), it,
[](int e) -> int
{
return -1;
});
// now the array contains:
// {1,2,3,4,9,10,-1,-1,-1,-1}

How to iterate through vector size and assign to new vector?

So I have a vector container, and I generate a random string (as of right now it's
just asterisks for the sake of me being able to easily see the differences in size) to assign through the vector. All is fine and dandy, got everything working with that..
When I pass the vector to a function that is supposed to iterate through and assign the size
of each element in the vector to a new vector, I always get an error. What is the best way to do this?
The code below is not my original attempt, but I'm late for class and have to run. So as of right now, here's how I'm trying to do it.
vector<int> siz;
int length = contain.size();
for (vector<string>::iterator i = contain.begin(); i != contain.end(); ++i){
siz.push_back(contain.size());
}
for (vector<int>::iterator j = siz.begin(); j != siz.end(); ++j){
cout << *j << endl;
}
You need to get the size of each individual element, rather than the length of the container vector.
Your i variable is an iterator on the container vector, which operates essentially as a pointer to each element. In the body of your loop, access the size of the object i points to, to get the size of that object.
vector<int> siz;
for (vector<string>::iterator i = contain.begin(); i != contain.end(); ++i){
siz.push_back(i->size());
}
If I understand your intention, you want a vector siz that contains the length of each string in the vector contain, correct? If so, you do not want to do contain.size() because that is just the length of your string vector. To get the size of each string, see below.
vector<int> siz;
for (vector<string>::iterator i = contain.begin(); i != contain.end(); ++i){
string currentString = *i;
siz.push_back(currentString.size());
}

Create std::vector with brackets for default size

#include <iostream>
#include <vector>
int main()
{
static const unsigned TOTAL = 4;
std::vector<int> v[TOTAL];
v[2].push_back(37);
//std::cout << v.size(); error
std::cout << v[0].size();
std::cout << v[2].size();
return 0;
}
Is is valid to instatnitate std::vector with bracket like in the code above?
MSVS and ideone compile it just fine, but vector is messed up (see error line).
I know I can use resize, but what is going on here?
You are creating a TOTAL sized array of vectors.
What you need is
std::vector<int> v(TOTAL);
This constructs a vector with TOTAL zero-initialized ints.
Then,
std::cout << v.size() << std::endl; // prints 4
std::cout << v[0] << std::endl; // prints 0
and so on.
It is valid to instantiate std::vector with bracket like in the code, but with different meanings.
std::vector<int> v[TOTAL];
Here you defined a vector v of size=TOTAL, each element of which is a vector<int>. Initially, these TOTAL vector<int>s are all empty (i.e. size=0).
After you call v[2].push_back(37);, v[2] will become a vector<int> of size=1 with a value 37 in it.
So the output you for the following will be 0 and 1.
std::cout << v[0].size();
std::cout << v[2].size();
If you want to call size(), you should call v[i].size() or define it as vector<int> v(TOTAL); (v is a vector of size=TOTAL, each element of which is an int).
I know I can use resize, but what is going on here?
you are basicly creating an array of type std::vector<int>, just as in here:
int arr[TOTAL];
Is is valid to instatnitate std::vector with bracket like in the code above?
you can have an array of vectors, but from your post it is not what you are after.
If you want to give your vector some initial size then use
std::vector<int> v(TOTAL);
this will set initial size of your vector to TOTAL, and value initialize all elements (set them to zero).
But you might actually want to:
std::vector<int> v;
v.reserve(TOTAL); // this is not necessary
// v.size() is zero here, push_back will add elements starting from index 0
because in case of std::vector<int> v(TOTAL); your push_back will start adding from index TOTAL.

Two dimensional vector of integer C++. What's wrong?

I have trouble with two dimensional vector. Example:
vector < vector<int> > data;
int i = 0;
int int_value;
while (i < 10 )
{
cin >> int_value;
data[i].push_back (int_value);
}
I want using push_back for back insert and then I want use data [i][j]. Where is the problem?
You need to initialize vector data before using data[i]. Otherwise, the vector is empty and accessing data[i] is out of range. Also, you need to increment i inside the while loop:
vector < vector<int> > data(10); // creates a vector of size 10,
// each element being an empty vector of int's
int int_value;
for (int i=0; i < 10; i++)
{
cin >> int_value;
data[i].push_back (int_value); // add int_value to the ith vector
}
After the loop, each vector contains one int value entered by the user.
data[i] does not exist, because the empty constructor of vector creates a vector of size 0. So when you call data[i] this will be out of bounds. Just like a one dimensional vector first allocate enough elements for data. In your case it seems you need to have data of size 10:
vector < vector<int> > data(10);
Also you never increase i in the while loop which it seems will lead to infinite loop.
You have an empty vector of vectors, and you are trying to access its elements (data[i]). Obviously, you can't do that before you add some (via push_back, resize or some other method of data itself).
The problem is that data[i] does not exist. First you need to push a vector<int> into the vector< vector<int> > vector, then you can add integers to it.
vector < vector<int> > data;
data is an empty vector which holds vector<int>.
data[i].push_back (int_value);
data is empty. So, doing data[i] leads to undefined behavior.