I have been practicing with vectors, when I try to print the values with the length set, output is 0, but when I try to print the values without the length set, it shows correct values.
A question like this has been answered before but I didnt really get it.
Here's the code:-
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int size,val;
cout << "Enter vector length " << endl;
cin >> size;
vector<int> vec(size);
for(int i = 0; i < size; i++){
cout << "Enter number for index " << i+1 << endl;
cin >> val;
vec.push_back(val);
}
for(int i = 0; i < size; i++){
cout << "Numeber at index " << i+1 << " is " << vec[i] << endl;
}
}
Output:-
Enter vector length
3
Enter number for index 1
1
Enter number for index 2
2
Enter number for index 3
3
Numeber at index 1 is 0
Numeber at index 2 is 0
Numeber at index 3 is 0
With value not set:-
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int size,val;
cout << "Enter vector length " << endl;
cin >> size;
vector<int> vec;
for(int i = 0; i < size; i++){
cout << "Enter number for index " << i+1 << endl;
cin >> val;
vec.push_back(val);
}
for(int i = 0; i < size; i++){
cout << "Numeber at index " << i+1 << " is " << vec[i] << endl;
}
}
Output:-
Enter vector length
3
Enter number for index 1
1
Enter number for index 2
2
Enter number for index 3
3
Numeber at index 1 is 1
Numeber at index 2 is 2
Numeber at index 3 is 3
Help!!!
When you call push_back on a vector you are adding items to the end of it.
In the second example you push_back to it 3 times to the length of the vector is 3.
[] <-- vector is constructed
[ 1 ] <-- push_back(1)
[ 1, 2 ] <-- push_back(2)
[ 1, 2, 3 ] <-- push_back(3)
In the first example, when you set the length to be 3, those values are initialized to zero. Then you push_back 3 times so the final length of the vector is 6 and the first 3 values are still 0.
[ 0, 0, 0 ] <-- vector is constructed
[ 0, 0, 0, 1 ] <-- push_back(1)
[ 0, 0, 0, 1, 2 ] <-- push_back(2)
[ 0, 0, 0, 1, 2, 3 ] <-- push_back(3)
If you want to increase the CAPACITY of the vector but not the SIZE you want vector.reserve
There are two ways to do what you are trying to do.
One is the way you did it in your second trial.
The other is to modify your first trial's code:
Instead of vec.push_back(val);, try accessing the index directly:
vec.at(i) = val;
Both methods work fine.
The issue with your first trial was you resized a vector then appended values instead of doing what you thought it would do.
Basically, the vector was resized to size so all the elements from index 0 to size-1 were all set to 0, which is the default int value for vectors. After that, you appended new integers to the back of the vector. The reason your second trial worked is because the size of the vector started at 0, then you appended new integers to the back with your calls to push_back(int) in your for loop.
An important note: I would rephrase your output. Instead of saying "Number at index" << i + 1, change it to Number at element. The index numbering starts at 0. Element numbering starts at 1. As in: element 1 is located at index 0.
Related
I have std::vector<bool> v
I want to resize it and put false value to all its elements. How can I do it efficiently (without loop)
How can I do it?
If v has already been constructed, you can use assign method to achieve your goal.
v.assign(count, false);
NOTE: vector<bool> might be space-efficient optimized, and behaves different than other types of vector, e.g. the underlying storage might not be contiguous. And you might want to replace it with vector<int> or bitset<N>. You can check the doc for detail.
You can use the following approach
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<bool> v(5,true);
cout << "Initial size = " << v.size() << endl;
/* displaying Initial vector values */
for (int i = 0; i < v.size(); ++i)
cout << v[i] << " ";
cout<<endl;
/*
Resize it to required length
Parameters:
1st argument – it is a new container size, expressed in a number of elements.
2nd argument – if this parameter is specified then new elements are
initialized with this value.
*/
v.resize(10,false);
cout << "Size after resize = " << v.size() << endl;
/* displaying current vector values */
for (int i = 0; i < v.size(); ++i)
cout << v[i] << " ";
cout<<endl;
/*
assign new values to the vector
1. length upto which new values are to be assigned
2. value to be assign
*/
v.assign(v.size(),false);
cout << "size after assign = " << v.size() << endl;
/* display modified vector values */
for (int i = 0; i < v.size(); ++i)
cout << v[i] << " ";
return 0;
}
Ouput:
Initial size = 5
1 1 1 1 1
Size after resize = 10
1 1 1 1 1 0 0 0 0 0
size after assign = 10
0 0 0 0 0 0 0 0 0 0
I need to Write a C ++ program that prompts the user to enter 10 integers in the array.
Input numbers are: 0, 1 or 2.
The program should extract the array that is entered on the screen Arrange the array of elements 0, 1, and 2 so that the array places all 0 in the first places, then all 1s
and all 2 as the last.
Arranged array displays on the screen.
Have been struggling over this for few hours now. Im stuck and dont know how to show Output .
Input should be for example 0 0 1 0 1 2 2 2 0 1
Output 0000111222
HOW?
int main ()
{
int t [N], i, ;
cout << "Enter 10 arrays from 0-2" << endl;
cout << "Original array:";
for (i = 0; i <N; i ++)
{
cin >> t [i];
}
if (t [i]> = 0 && t [i] <= 2)
{
cout << "Rearranging elements of array:" << ? << endl;
}
cout << "End of the program!"
return 0;
}
when you do
if (t [i]> = 0 && t [i] <= 2)
i equals N so you access out of the array, and of course that does not sort the array
You do not check if cin >> t[i] success so if the user enter something else than an int all the entries from the current will not be set (they will be 0 in case you use a std::vector)
A first way is to do without taking account the range 0..2, replace int t[n] by std::vector<int> t(N) and use sort(t.begin(), t.end()) to sort your array
The complexity is O(N*log(N)) (here N is 10)
For instance :
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define N 10
int main ()
{
vector<int> t(N);
size_t i; // size_t the right type for an index
cout << "Enter 10 values in range 0..2" << endl;
for (i = 0; i < N; ++i)
{
for (;;) {
cout << "value #" << i << ':';
if (!(cin >> t[i])) {
cerr << "not a number" << endl;
cin.clear(); // raz error
string s;
cin >> s; // skip bad input
}
else if ((t[i] < 0) || (t[i] > 2))
cerr << "value out of range" << endl;
else
break;
}
}
cout << "Original array:";
for (i = 0; i < N; ++i) cout << ' ' << t[i]; // old way to do
cout << endl;
sort(t.begin(), t.end());
cout << "Sorted array:";
for (auto v : t) cout << ' ' << v; // new way to do
cout << endl;
cout << "End of the program!" << endl;
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall s.cc
pi#raspberrypi:/tmp $ ./a.out
Enter 10 values in range 0..2
value #0:aze
not a number
value #0:-2
value out of range
value #0:3
value out of range
value #0:2
value #1:0
value #2:1
value #3:2
value #4:0
value #5:2
value #6:1
value #7:0
value #8:0
value #9:1
Original array: 2 0 1 2 0 2 1 0 0 1
Sorted array: 0 0 0 0 1 1 1 2 2 2
End of the program!
A second way considering a range [min .. max] not too large is to count the number of each value then fill the array to respect these counts
The complexity is O(2N) (here N is 10)
For instance :
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
#define MIN 0
#define MAX 2
#define N 10
int main ()
{
vector<int> t(N);
size_t i; // size_t the right type for an index
cout << "Enter 10 values in range " << MIN << ".." << MAX << endl;
for (i = 0; i < N; ++i)
{
for (;;) {
cout << "value #" << i << ':';
if (!(cin >> t[i])) {
cerr << "not a number" << endl;
cin.clear(); // raz error
string s;
cin >> s; // skip bad input
}
else if ((t[i] < MIN) || (t[i] > MAX))
cerr << "value out of range" << endl;
else
break;
}
}
cout << "Original array:";
for (auto v : t) cout << ' ' << v;
cout << endl;
// count numbers
vector<size_t> counts(MAX - MIN + 1);
for (auto v : t) counts[v - MIN] += 1;
// fill again
i = 0;
for (int r = MIN; r <= MAX; ++r) {
size_t n = counts[r - MIN];
while (n--) t[i++] = r;
}
cout << "Sorted array:";
for (auto v : t) cout << ' ' << v;
cout << endl;
cout << "End of the program!" << endl;
return 0;
}
Compilation and execution :
pi#raspberrypi:/tmp $ g++ -pedantic -Wextra -Wall s2.cc
pi#raspberrypi:/tmp $ ./a.out
Enter 10 values in range 0..2
value #0:a
not a number
value #0:3
value out of range
value #0:0
value #1:2
value #2:1
value #3:1
value #4:2
value #5:2
value #6:2
value #7:0
value #8:1
value #9:2
Original array: 0 2 1 1 2 2 2 0 1 2
Sorted array: 0 0 1 1 1 2 2 2 2 2
End of the program!
Specifically for values between 0 and 2 (in fact for 3 possible values) as said in a remark by #PaulMcKenzie you can use the Dutch national flag problem and look at that question : R G B element array swap
The complexity is O(N) (here N is 10)
As a beginner, you may want to try this (this is the simplest solution I could think of without using other libraries):
int main () {
const int size = 10;
int arr[size], temp = 0;
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
for (int j = 0; j < size - 1; j++) {
for (int k = 0; k < size - j - 1; k++) {
if(arr[k] > arr[k+1]) {
temp = arr[k];
arr[k] = arr[k+1];
arr[k+1] = temp;
}
else
continue;
}
}
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
return 0;
}
I hope this helps you.
1st answer is too difficult for me, im only beginner not knowing what im doing yet.
2nd answer is to that direction where it should be right but i need to put in that input cant be more than 2 or less than numeber 0, thats the problem now :D
Im sorry, i just cant get to that point where i understand that syntax.
So I was learning about the stlibrary and graphs, and so I found out that graphs could be represented as a vector of lists which could be like this, where the 1 2 3 4 5 6 are the vertices, and from the vertice 1 I could go to the number 2, from the 3 to the 6, etc.
1 2 3 4 5 6
2 6 1 2
2
But, I already saved these values in the vector list, how could I loop through it to get the graph? My vector list is called _verticesEdges.
Like, to get an output like this:
Vertice 1: 2
Vertice 2:
Vertice 3: 6
Vertice 4: 1 2
Vertice 5:
Vertice 6: 2
Appreciate your help!
Assuming you have stored from index 1 to n (that means size of 0th index of your vector is zero), where n is number of vertices,
for (int i = 1; i <= n; i++)
{
cout << "Vertex " << i << ": ";
for (int j=0; j< _verticesEdges[i].size(); j++)
cout << _verticesEdges[i][j] << " ";
cout << "\n";
}
Something like this
std::vector<std::list<int>> vecOfLists;
// fill vecOfLists;
for (size_t i = 0; i < vecOfLists.size(); ++i) {
std::cout << "Vertice " << i + 1 << ": ";
for (int num : vecOfLists[i]) {
std::cout << num << " ";
}
std::cout << std::endl;
}
I am using usual for for iterating through lists, since index is required, and using range-based for for iterating through list, since this is better and modern way to iterate through whole container if you don't require indexes.
I'm trying to solve one of the questions on a task sheet I've been received, to help me further in my understanding of C++ code from my class.
The question is (and I quote):
Write a program that:
Asks the user to enter 10 numbers between 1 and 5 into an array and displays the array on screen
Creates a second array of size 5 and fills it with zeros
Counts how many 1s, 2s, , … 5s have been entered into the first array and stores this number in the second array.
Displays the second array as shown in the example below.
The problem is how to go about checking how many times a number was entered. I was thinking of a for loop, but the way I wrote it is fundamentally incorrect, so I find myself struggling to see the mistake I am having. Perhaps I am missing something simple? Any help would be great.
Here is my (terrible) for loop attempt, so you can see my error.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int input[10];
const int MAX_NO = 5;
int COUNT[5] = { 0,0,0,0,0 };
int count = 10;
for (int i = 0; i < count; i++)
{
cout << "Please enter a number for value " << i + 1 << " :";
cin >> input[i];
while (input[i] < 1 || input[i] > 5)
{
cout << "Error: Enter another number between 1 and 5: ";
cin >> input[i];
}
}
cout << endl << "You entered ";
for (int i = 0; i < count; i++)
{
cout << input[i] << " ";
}
cout << "\n";
// show how many times 1 number appears
for (int i = 1; i <= 5; i++)
{
if (input[i] == i)
{
COUNT[i]++;
}
}
for (int i = 0; i < MAX_NO; i++)
{
cout << i + 1 << " appears " << COUNT[i]
<< " times in the input" << endl;
}
cout << endl;
system("pause");
return 0;
}
Put
COUNT[ input[i]-1 ]++;
in your first loop (after validation). Once you do that, you don't need a second loop to tally up the results.
This works from the inside out by first getting what input[i] is, then using it to modify the (input[i]-1)'th location in the COUNT array. If the user enters 4 on the first run of the loop, then i == 0 and input[i] == 4. Since arrays are 0-based, it will increment COUNT[input[i]-1] which in this case is COUNT[4-1] == COUNT[3].
After your initial loop runs the number of 1's will be in COUNT[0], the number of 2's will be in COUNT[1] and so on.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
//declare a constant values
int input[10];
int count = 10; //all constant MUST be in capital letters
//second array filled with zeros
const int MAX_NO = 5;
int COUNT[5] = { 0, 0, 0, 0, 0 };
//ask user for 10 input values
for (int i = 0; i < count; i++)
{
cout << "Please enter a number for value " << i + 1 << " :";
cin >> input[i];
//check if input numbers are between 1 and 5 inclusive
while (input[i] < 1 || input[i] > 5)
{
cout << "Error: Enter another number between 1 and 5: ";
cin >> input[i];
}
/* show how many times 1 number appears.
this section should be in the main loop which would enable the program to check how many times a
number is entered so that it is stored in the second array. changed i to secondCount because this is the counting index of the second array not the first which you've called i (one of the reason you'd all zero as output when u ran your code)*/
for (int secondCount = 1; secondCount <= MAX_NO; secondCount++)
{
if (input[i] == secondCount)
{
COUNT[secondCount-1]+= 1; //use minus 1 from i and increment. += 1 is the same as COUNT++
}
}
}
//display number entered in the first array
cout << endl << "You entered ";
for (int i = 0; i < count; i++)
{
cout << input[i] << " ";
}
cout << "\n";
//display how many times a number is entered.
for (int secondCount = 0; secondCount < MAX_NO; secondCount++)
{
cout << secondCount + 1 << " appears " << COUNT[secondCount]
<< " times in the input" << endl;
}
cout << endl;
system("pause");
return 0;
}
OUTPUT:
Please enter a number for value 1 = 1
Please enter a number for value 2 = 1
Please enter a number for value 3 = 1
Please enter a number for value 4 = 2
Please enter a number for value 5 = 3
Please enter a number for value 6 = 2
Please enter a number for value 7 = 4
Please enter a number for value 8 = 4
Please enter a number for value 9 = 3
Please enter a number for value 10 = 2
You entered: 1 1 1 2 3 2 4 4 3 2
1 appears 3 times in the input
2 appears 3 times in the input
3 appears 2 times in the input
4 appears 2 times in the input
5 appears 0 times in the input
for (int i = 1; i <= 5; i++)
{
if (input[i] == i)
{
COUNT[i]++;
}
}
Let's examine what this is doing. It starts by checking input[1]. (This should be input[0] as array indices start at 0). Then it checks if input[1] is equal to 1. If it is, then it increments COUNT[1].
Next, it checks input[2]. Then it checks if input[2] is equal to 2. If it is, it increments COUNT[2]. And so on until it has gone through input[5].
Do you see the problem with this? You're only checking the first 5 inputs and only checking them against a single value.
Write a program that asks the user to input the
dimension (n) of the square (n x n) array, and then asks the user to input the values 1 row
at a time. For example:
“Enter the size of a 2D array: ”
“Enter the values in the array for row 1, separated by a space, and press enter: ”
- Limit the size of the array to maximum 10 x 10 and check for errors.
Once the array is initialized, check if there is any negative element in the array and display the result:
If there is no negative value: “All values are non-negative!”
If there are # negative values: “There are # negative values!” … where # is the
number of negative values found.
Example runs:
Enter the size of a 2D array: 4
Enter the values in the array for row 1, separated by a space, and press enter: 1 5 6 3
Enter the values in the array for row 2, separated by a space, and press enter: -5 6 -12 5
Enter the values in the array for row 3, separated by a space, and press enter: 9 4 -3 1
Enter the values in the array for row 4, separated by a space, and press enter: 7 5 -3 9
There are 4 negative values!
Enter the size of a 2D array: 12
ERROR: your array is too large! Enter 1 to 10
Here is what I have so far but I can't figure how to enter the info one row at a time.
Do I enter the values of into two separate arrays then try to combine them? But the values need to stay in their receptive rows.
Thanks
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
cout << "please enter the size of the 2D array" << endl;
cin >> num;
while (num < 1 || num > 10)
{
cout << "You have entered an invalid number that is less than 10"<< endl;
cout << "Enter a new # " << endl;
cin >> num;
}
cout <<"Enter a sequence of numbers separated by spaces" << endl;
int c = 0;
int arr[num][num];
for(int i = 0; i < num; i++)
{
for(int j = 0; j < num; j++)
{
cin >> arr[i][j];
if(arr[i][j] < 0 )
{
c = c+1;
}
}
}
for(int i=0; i < num; i++)
{
for(int j=0; j < num; j++)
{
cout << arr[i][j] << endl;
}
}
cout << c << endl;
return 0;
}
With your code, it is already capable of reading one row of integers each time. In fact you can type in each integer and press enter and then type in the next...and so on. You can also type in a whole row of integers, the program will accept it as long as the count is correct.
For example, if I want to type in a 2x2 array,
I can either type in:
1
2
3
4
or do:
1 2
3 4
It will both work.
A couple of things:
Since the dimension of the array is dynamic, this line isn't valid (see this link for more: http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/):
int arr[num][num];
As such, you need either an array of pointers (which point to arrays), or a vector with which to allocate and manage the memory (given that this is an assignment, you may not be able to use a vector, and will have to use a pointer instead).
Regarding your question:
Do I enter the values of into two separate arrays then try to combine
them?
You don't have to do so.
If you use a pointer (technically: an array of pointers which point to arrays) or a vector, then you should be able to directly access and modify the contents at a particular row and column index.
Example: if you're going the pointer route:
#include <iostream>
#include <cstdlib>
int main() {
std::size_t size;
std::cout << "Enter a dimension: " << std::endl;
std::cin >> size;
int **arr = new int*[size];
//allocate the memory for the columns:
for (int i = 0; i < size; ++i) {
//remember, it's an array of pointers which in turn point to arrays
//so, that's why we have to allocate the memory for each row manually
arr[i] = new int[size];
}
//now you can alter the data in the array:
for (int i = 0; i < size; ++i) {
//the following for loop is how you would prompt the user to enter the value for a specific row:
for (int j = 0; j < size; ++j) {
std::cout << "Enter a value for row " << i << " and column " << j << std::endl;
std::cin >> arr[i][j];
}
}
//now print the entire thing:
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
std::cout << arr[i][j] << " ";
}
//print a new line at the end of each row:
std::cout << std::endl;
}
//free the memory we've allocated:
for (int i = 0; i < size; ++i) {
delete [] arr[i];
}
delete [] arr;
return 0;
}
However, as you've noticed: this has a lot of boilerplate code. If the option is available to you, it's arguably a better idea to use a vector instead.
For more on that discussion, consult these:
When would you use an array rather than a vector/string?
When to use vectors and when to use arrays in C++?