Displaying contents of a vector container in C++ - c++

The following is a C++ program using STL vector container. Just wanted to know why the display() function is not printing the vector contents to the screen. If displaying the size() line is commented out, display() function works fine.
#include <iostream>
#include <vector>
using namespace std;
void display(vector<int> &v)
{
for(int i; i<v.size(); i++)
{
cout << v[i] << " ";
}
cout << "\n" << endl;
}
int main()
{
vector<int> v;
cout << "Size of Vector=" << v.size() << endl;
//Putting values into the vector
int x;
cout << "Enter five integer values" << endl;
for(int i; i<5; i++)
{
cin >> x;
v.push_back(x);
}
//Size after adding values
cout << "Size of Vector=" << v.size() << endl;
//Display the contents of vector
display(v);
v.push_back(6);
//Size after adding values
cout << "Size of Vector=" << v.size() << endl;
//Display the contents of vector
display(v);
}
Output:
Size of Vector=0
Enter five integer values
1
2
3
4
5
Size of Vector=5
Size of Vector=6

There is an idiomatic way for printing a vector out.
#include <algorithm>
#include <iterator>
//note the const
void display_vector(const vector<int> &v)
{
std::copy(v.begin(), v.end(),
std::ostream_iterator<int>(std::cout, " "));
}
This way is safe and doesn't require you to keep track of the vectors size or anything like that. It is also easily recognisable to other C++ developers.
This method works on other container types too that do not allow random access.
std::list<int> l;
//use l
std::copy(l.begin(), l.end(),
std::ostream_iterator<int>(std::cout, " "));
This works both ways with input too consider the following:
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
std::cout << "Enter int end with q" << std::endl;
std::vector<int> v; //a deque is probably better TBH
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter<int>(v));
std::copy(v.begin(), v.end(),
std::ostream_iterator<int>(std::cout, " "));
}
This version doesn't require any hard coding of size or manual management of the actual elements.

You are not initializing your variables. for(int i = 0; not for(int i;

I think this is the easiest way to go:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> v;
int x;
cout << "Enter five integer values" << endl;
for(int i=0; i<5; i++)
{
cin >> x;
v.push_back(x);
}
for (int i = 0; i < (int)v.size(); i++)
cout<< v.at(i) <<endl;
}

If you use compiler versions g++ 11 or more than then you simply use:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> v;
int x;
cout << "Enter five integer values" << endl;
for(int i=0; i<5; i++)
{
cin >> x;
v.push_back(x);
}
for (auto i: v)
cout<< i <<endl;
}

I have found printing using for_each() very easy to understand and intuitive
#include<vector>
#include<algorithm>
using namespace std;
main(){
vector<int> foo_bar{1,2,3,4,5};
auto print_array = [](const auto& o) {cout << o << " "; };
for_each(foo_bar.begin(), foo_bar.end(), print_array);
}

Related

Fill up a vector with input from a user

I am learning c++ and i have a problem with filling a vector with the input from the user. wWenever i try to run my code, a window pops-up with 'vector subscript out of range' written in it.
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int s(0), values(0);
vector <int> grades;
cout << "Enter the number of grades you want to enter: \n";
cin >> s;
cout << "Enter the values:";
for (int i(0); i < s; i++)
{
cin >> values;
grades.push_back(values);
}
int grades_size(grades.size());
int average(0);
for (int m(0); m <= grades_size; m++)
{
average += grades[m];
}
average /= grades_size;
cout << "Your average is" << average;
return 0;
}
You can read things from input using streams.
The following example shows how to use the succinct syntax of ranges to do that:
#include <iostream>
#include <range/v3/view/istream.hpp>
#include <range/v3/range/conversion.hpp>
int main()
{
auto vec = ranges::istream<int>(std::cin) | ranges::to_vector;
for (auto elem : vec) {
std::cout << elem << std::endl;
}
}

Is there a better way to print vector elements using iterator and reverse_iterator?

I have a program that creates a std::vector and adds the given values to it using push_back(). The expected output is to print the vector values in default order and reverse order using an iterator and reverse iterator. The output is absolutely correct but I was just wondering if there's a better way to do this: :-
#include <iostream>
#include <vector>
using namespace std;
vector<int> myvector;
int i;
int main()
{
int n;
cin>>n;
int input;
for (i = 0; i < n; i++)
{
cin >> input;
myvector.push_back(input);
}
for (int i = 0; i < n; i++)
{
cout<<" "<<myvector[i]; //prints user vector input
}
cout<<endl;
typedef vector<int>::iterator iter_type;
iter_type from (myvector.begin());
iter_type until (myvector.end());
reverse_iterator<iter_type> rev_until (from);
reverse_iterator<iter_type> rev_from (until);
while (rev_from != rev_until)
cout << ' ' << *rev_from++; //prints reversed vector
return 0;
}
Figured out an alternate method
#include <vector>
#include <iostream>
int main()
{
int n;
std::cin>>n;
std::vector<int> g1;
int a[40];
std::vector<int>::iterator i;
std::vector<int>::reverse_iterator it;
for(int i=0;i<n;i++)
{
std::cin>>a[i];
g1.push_back(a[i]);
}
for (auto i = g1.begin(); i != g1.end(); ++i)
std::cout << *i << " ";
std::cout<<"\n";
for (auto it = g1.rbegin(); it != g1.rend(); ++it)
std::cout << *it << " ";
return 0;
}
You can do as follows:
Option - 1
Use range-based for
loop for
both inputting and printing(normally) the element of vector. And using
std::for_each
function, along with const reverse iterator and a
lambda, reverse print the elements of the vector.
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
int n; std::cin >> n;
std::vector<int> myvector(n);
for (int& element : myvector) std::cin >> element;
for (const int element : myvector) std::cout << element << " "; std::cout << std::endl;
std::for_each(myvector.crbegin(), myvector.crend(), [](const int element) { std::cout << element << " "; }); //prints reversed vector
return 0;
}
Option - 2
Another, complete iterator way of doing is using std::istream_iterator and std::ostream_iterator, also the algorithum functions std::copy and std::copy_n.
#include <algorithm>
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
int n; std::cin >> n;
std::vector<int> myvector; myvector.reserve(n);
std::copy_n(std::istream_iterator<int>(std::cin), n, std::back_inserter(myvector));
std::copy(myvector.cbegin(), myvector.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl;
std::for_each(myvector.crbegin(), myvector.crend(), [](int element){ std::cout << element << " ";}); //prints reversed vector
return 0;
}
Option - 3 (Update)
After seeing your edit/update in your question, I realize that you are trying to print elements using traditional iterator-for-loop. If so, you do not need extra array int a[40];. Instead, allocate and initilze the vector g1 with size n and can input the elements using the iterator as follows:
#include <iostream>
#include <vector>
int main()
{
int n; std::cin >> n;
std::vector<int> g1(n); // change here
for (auto iter = g1.begin(); iter != g1.end(); ++iter) std::cin >> *iter; // change here
for (auto iter = g1.cbegin(); iter != g1.cend(); ++iter) std::cout << *iter << " "; std::cout << "\n";
for (auto iter = g1.crbegin(); iter != g1.crend(); ++iter) std::cout << *iter << " ";
return 0;
}
Side-Notes:
Do not practice coding with using namespace std;, (see the reason here.)
Try to maximum avoid using global variables. In your case,
definitely no need.

Struggling with creating a function that stores user input to any chosen vector (using c++)

This is what I have so far...
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> list1;
vector<int> list2;
void listAdd(int n, vector<int>v) {
while (n != 0) {
v.push_back(n);
cin >> n;
}
}
void printList(vector<int>v) {
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
}
int main() {
int nInput;
cout << "Please enter numbers for list1... (end with a '0') " << endl;
cin >> nInput;
listAdd(nInput, list1);
printList(list1);
return 0;
}
I basically want all numbers entered by the user (until they enter a 0) to be stored in the vector called list1. Then later i can call the same function to add numbers to another vector...
Help really appreciated :)
you need to pass the vectors by reference
void listAdd(int n, vector<int>& v);
void printList(vector<int>& v);

Sum of elements in a vector?

How would I find the sum of the elements in a vector that was inputted by a user? I tried searching for a method to do so everywhere online but couldn't really find one online that explained it really well, nor was it explained in class too much unfortunately.
So I basically have the vectors inputted by a user here, but I have no idea how to use it to take the sum of it? (printvector is only there because I have to present what the user put in to the user before telling the user the sum)
#include <iostream>
#include <vector>
using namespace std;
void fillVector(vector<int>&);
void printVector(const vector<int>&);
int main()
{
vector<int> VectorQuantities;
fillVector(VectorQuantities);
printVector(VectorQuantities);
return 0;
}
void fillVector(vector<int>& newVectorQuantities)
{
cout << "Type in a list of numbers, and type in -1 as the last number when you are finished: ";
int input;
cin >> input;
while (input != -1) {
newVectorQuantities.push_back(input);
cin >> input;
}
cout << endl;
}
void printVector(const vector<int>& newVectorQuantities) {
cout << "Vector: ";
for (unsigned int i=0; i < newVectorQuantities.size(); i++) {
cout << newVectorQuantities[i] << " ";
}
cout << endl;
}
You can use std::accumulate().
#include <algorithm>
std::vector<int> vec = ...;
int vecSum = std::accumulate(std::begin(vec), std::end(vec), 0);
The accumulate() function is really just a left fold, and by default it uses the + function to combine elements.
Try this:
void printSum(const vector<int>& newVectorQuantities) {
cout << "Sum: ";
int sum = 0;
for (unsigned int i=0; i < newVectorQuantities.size(); i++) {
sum = sum + newVectorQuantities[i];
}
cout << sum << " ";
}
(Using your style for the function, not modern C++.)

I can't figure out why for-loop doesn't work on this code

I want to make the vector( mycount) that indicates frequency of the elements in myvec. Can you please let me know what is wrong?
#include <iostream>
#include <vector>
#include <cstdlib>
#include <functional>
#include <algorithm>
using namespace std;
int main() {
int num;
cout << "How many numbers do you want to read in?" << endl;
cin >> num;
vector<int> myvec(num);
std::generate(myvec.begin(), myvec.end(), []()->int {return rand(); });
for (int i = 0; i < num; ++i) {
vector<int> mycount[i] = count(myvec.begin(), myvec.end(), myvec[i]);
cout << mycount[i] << endl;
}
return 0;
}
I suspect you meant to use:
vector<int> myvec(num);
// Create a vector for storing the counts as well.
vector<int> mycount(num);
std::generate(myvec.begin(), myvec.end(), []()->int {return rand(); });
for (int i = 0; i < num; ++i) {
// Get the counts of the element at this index and store it.
mycount[i] = count(myvec.begin(), myvec.end(), myvec[i]);
cout << mycount[i] << endl;
}
your mycount definition is wrong. Check the below code
#include <iostream>
#include <vector>
#include <cstdlib>
#include <functional>
#include <algorithm>
using namespace std;
int main() {
int num;
cout << "How many numbers do you want to read in?" << endl;
cin >> num;
vector<int> myvec(num);
std::generate(myvec.begin(), myvec.end(), []()->int {return rand(); });
vector<int> mycount(num); \\declare mycount with num elements
for (int i = 0; i < num; ++i) {
\\populate the counter for each element
mycount[i] = count(myvec.begin(), myvec.end(), myvec[i]);
cout << mycount[i] << endl;
}
return 0;
}