Is there a way of printing arrays in C++?
I'm trying to make a function that reverses a user-input array and then prints it out. I tried Googling this problem and it seemed like C++ can't print arrays. That can't be true can it?
Just iterate over the elements. Like this:
for (int i = numElements - 1; i >= 0; i--)
cout << array[i];
Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.
Use the STL
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <ranges>
int main()
{
std::vector<int> userInput;
// Read until end of input.
// Hit control D
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(userInput)
);
// ITs 2021 now move this up as probably the best way to do it.
// Range based for is now "probably" the best alternative C++20
// As we have all the range based extension being added to the language
for(auto const& value: userInput)
{
std::cout << value << ",";
}
std::cout << "\n";
// Print the array in reverse using the range based stuff
for(auto const& value: userInput | std::views::reverse)
{
std::cout << value << ",";
}
std::cout << "\n";
// Print in Normal order
std::copy(userInput.begin(),
userInput.end(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
// Print in reverse order:
std::copy(userInput.rbegin(),
userInput.rend(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
}
May I suggest using the fish bone operator?
for (auto x = std::end(a); x != std::begin(a); )
{
std::cout <<*--x<< ' ';
}
(Can you spot it?)
Besides the for-loop based solutions, you can also use an ostream_iterator<>. Here's an example that leverages the sample code in the (now retired) SGI STL reference:
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
using namespace std;
copy(foo,
foo + sizeof(foo) / sizeof(foo[0]),
ostream_iterator<short>(cout, "\n"));
}
This generates the following:
./a.out
1
3
5
7
However, this may be overkill for your needs. A straight for-loop is probably all that you need, although litb's template sugar is quite nice, too.
Edit: Forgot the "printing in reverse" requirement. Here's one way to do it:
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
using namespace std;
reverse_iterator<short *> begin(foo + sizeof(foo) / sizeof(foo[0]));
reverse_iterator<short *> end(foo);
copy(begin,
end,
ostream_iterator<short>(cout, "\n"));
}
and the output:
$ ./a.out
7
5
3
1
Edit: C++14 update that simplifies the above code snippets using array iterator functions like std::begin() and std::rbegin():
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
// Generate array iterators using C++14 std::{r}begin()
// and std::{r}end().
// Forward
std::copy(std::begin(foo),
std::end(foo),
std::ostream_iterator<short>(std::cout, "\n"));
// Reverse
std::copy(std::rbegin(foo),
std::rend(foo),
std::ostream_iterator<short>(std::cout, "\n"));
}
There are declared arrays and arrays that are not declared, but otherwise created, particularly using new:
int *p = new int[3];
That array with 3 elements is created dynamically (and that 3 could have been calculated at runtime, too), and a pointer to it which has the size erased from its type is assigned to p. You cannot get the size anymore to print that array. A function that only receives the pointer to it can thus not print that array.
Printing declared arrays is easy. You can use sizeof to get their size and pass that size along to the function including a pointer to that array's elements. But you can also create a template that accepts the array, and deduces its size from its declared type:
template<typename Type, int Size>
void print(Type const(& array)[Size]) {
for(int i=0; i<Size; i++)
std::cout << array[i] << std::endl;
}
The problem with this is that it won't accept pointers (obviously). The easiest solution, I think, is to use std::vector. It is a dynamic, resizable "array" (with the semantics you would expect from a real one), which has a size member function:
void print(std::vector<int> const &v) {
std::vector<int>::size_type i;
for(i = 0; i<v.size(); i++)
std::cout << v[i] << std::endl;
}
You can, of course, also make this a template to accept vectors of other types.
Most of the libraries commonly used in C++ can't print arrays, per se. You'll have to loop through it manually and print out each value.
Printing arrays and dumping many different kinds of objects is a feature of higher level languages.
It certainly is! You'll have to loop through the array and print out each item individually.
This might help
//Printing The Array
for (int i = 0; i < n; i++)
{cout << numbers[i];}
n is the size of the array
std::string ss[] = { "qwerty", "asdfg", "zxcvb" };
for ( auto el : ss ) std::cout << el << '\n';
Works basically like foreach.
My simple answer is:
#include <iostream>
using namespace std;
int main()
{
int data[]{ 1, 2, 7 };
for (int i = sizeof(data) / sizeof(data[0])-1; i >= 0; i--) {
cout << data[i];
}
return 0;
}
You can use reverse iterators to print an array in reverse:
#include <iostream>
int main() {
int x[] = {1,2,3,4,5};
for (auto it = std::rbegin(x); it != std::rend(x); ++it)
std::cout << *it;
}
output
54321
If you already reversed the array, you can replace std::rbegin and std::rend with std::begin/std::end, respectively, to iterate the array in forward direction.
It's quite straightforward to copy the array's elements to a suitable output iterator. For example (using C++20 for the Ranges version):
#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>
template<typename T, std::size_t N>
std::ostream& print_array(std::ostream& os, std::array<T,N> const& arr)
{
std::ranges::copy(arr, std::ostream_iterator<T>(os, ", "));
return os;
}
Quick demo:
int main()
{
std::array example{ "zero", "one", "two", "three", };
print_array(std::cout, example) << '\n';
}
Of course it's more useful if we can output any kind of collection, not only arrays:
#include <algorithm>
#include <iterator>
#include <iosfwd>
#include <ranges>
template<std::ranges::input_range R>
std::ostream& print_array(std::ostream& os, R const& arr)
{
using T = std::ranges::range_value_t<R>;
std::ranges::copy(arr, std::ostream_iterator<T>(os, ", "));
return os;
}
The question mentions reversing the array for printing. That's easily achieved by using a view adapter:
print_array(std::cout, example | std::views::reverse) << '\n';
// Just do this, use a vector with this code and you're good lol -Daniel
#include <Windows.h>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<const char*> arry = { "Item 0","Item 1","Item 2","Item 3" ,"Item 4","Yay we at the end of the array"};
if (arry.size() != arry.size() || arry.empty()) {
printf("what happened to the array lol\n ");
system("PAUSE");
}
for (int i = 0; i < arry.size(); i++)
{
if (arry.max_size() == true) {
cout << "Max size of array reached!";
}
cout << "Array Value " << i << " = " << arry.at(i) << endl;
}
}
If you want to make a function that prints every single element in an array;
#include <iostream>
using namespace std;
int myArray[] = {1,2,3,4, 77, 88};
void coutArr(int *arr, int size){
for(int i=0; i<size/4; i++){
cout << arr[i] << endl;
}
}
int main(){
coutArr(myArray, sizeof(myArray));
}
The function above prints every single element in an array only, not commas etc.
You may be wondering "Why sizeoff(arr) divided by 4?". It's because cpp prints 4 if there's only a single element in an array.
Related
i would like to make all the values in a std::vector true. I wrote 2 methods: the first one worked but the second did not. It tells me myproj.exe has triggered a breakpoint. Do you know what is the problem?
This one works:
void first(std::vector<bool>& vect, unsigned int n)
{
for (unsigned int i = 0; i < n; i++)
{
vect.push_back(true);
}
}
This one does not:
void secound(std::vector<bool>& vect, unsigned int n)
{
for(unsigned int i = 0; i < n; i++)
{
vect[i] = true; //crash here
}
}
In first case you call push_back which automatically increases size of vector.
In second case you trying to access vect[i] which does not exist as size of vector is 0.
Easiest way to fill vector here would be
vect = std::vector<bool>(n, true);
You can use the following std::vector's overload:
vector(size_type count, const T& value, const Allocator& alloc = Allocator());
where the first argument is the size of the std::vector and the second argument is the initial value.
Full code:
#include <vector>
#include <iostream>
int main() {
std::vector<bool> v(10, true);
for (auto i : v) {
std::cout << std::boolalpha << i << std::endl;
}
return 0;
}
std::vector<bool> v(10, true); will create a vector with 10 boolean true values.
Check it out live.
If you want to reinitialize the std::vector, these are the following options:
use std::fill like this std::fill(v.begin(), v.end(), true);
use std::vector::resize like this v.resize(10, true); if the std::vector is already initialized
use std::vector::assign like this v.assign(10, true);
The problem with the second function implementation is that if the vector is empty or there are less elements than the value of the second parameter then you may not use the subscript operator. Otherwise you have undefined behavior.
Also there is a logical difference between the implementations.
In the first function implementation new elements are appended to already existent elements of the vector. In the second function implementation existent elements are overwritten.
But in any case the both function implementations look not good. You could do the same operation using one method of the class std::vector.
Here is a demonstrative program.
#include <iostream>
#include <iomanip>
#include <vector>
void reset( std::vector<bool> &v, size_t n, bool value = false )
{
v.assign( n, value );
}
int main()
{
std::vector<bool> v;
reset( v, 5);
for ( const auto item : v )
{
std::cout << std::boolalpha << item << ' ';
}
std::cout << '\n';
reset( v, 5, true );
for ( const auto item : v )
{
std::cout << std::boolalpha << item << ' ';
}
std::cout << '\n';
return 0;
}
The program output is
false false false false false
true true true true true
You can make use of std::fill to do this. This is more idiomatic c++ than reassignment
#include <algorithm>
#include <vector>
#include <iostream>
int main()
{
std::vector<bool> v(8);
std::fill(v.begin(), v.end(), true);
}
This question already has answers here:
What's the best way to iterate over two or more containers simultaneously
(11 answers)
Closed 4 years ago.
I'm new to C++ and hence would need some help in accomplishing a certain task. The problem is, I have to iterate over three or more vectors simultaneously, like so:
#include <vector>
#include <iostream>
#include <string>
#include <boost/range/combine.hpp>
using namespace std;
int main(int, char**) {
vector<string> questions = {"Planet", "Rocket", "Galaxy"};
vector<string> answers = {"Planet", "Saturn", "Star"};
vector<int> count = { 12, 34, 79};
vector<int> score = { 324, 956, 289};
vector<int> result;
vector<int> subscore;
string a, q;
int c, s;
for ( const string q : questions ) {
int match = 0;
for( auto tuple : boost::combine(answers, count) ) {
boost::tie(a,c) = tuple;
if( q.substr(0,2) == a.substr(0,2)) {std::cout << q.substr(0,3) << " " << a.substr(0,3) << endl; match = c; }
else cout << "No match!" << '\n';
}
if( match ) { result.push_back(match); }
else result.push_back(0); subscore.push_back(0);
This approach works but I can't use it in the framework we are using.
Maybe someone here can point me to a similar solution that does not depend on boost but is still efficient.
Many thanks!
You can use good old index:
auto size = std::min( answers.size(), count.size() ); // or at least assert that size is equal
for( size_t i = 0; i < size; ++i ) {
const auto &a = answers[i];
const auto c = count[i];
// .. same as before
note this way you possibly avoiding to make 2 copies of std::string per iteration - answers -> tuple -> a
This seems a transform so in C++ you can use std::transform... for example:
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(int, char**) {
vector<string> questions = {"Planet", "Rocket", "Galaxy"};
vector<string> answers = {"Planet", "Saturn", "Star"};
vector<int> count = { 12, 34, 79};
vector<int> result;
for(const auto& q : questions)
{
transform(begin(answers), end(answers), begin(count), back_inserter(result),
[&q](const auto& answer, auto count)
{
if (q.substr(0, 2) == answer.substr(0, 2))
{
std::cout << q.substr(0,3) << " " << answer.substr(0,3) << endl;
return count;
}
else
cout << "No Match!" << endl;
return 0;
});
}
}
Now the results vector holds all results. back_inserter is used in order to dynamically grow the result std::vector.
I'm trying to manipulate a set of elements in vectors in c++.
vector <int> vectorOfValue;
vectorOfValue.push_back(1);
vectorOfValue.push_back(2);
vectorOfValue.push_back(3);
vectorOfValue.push_back(4);
vectorOfValue.push_back(5);
vectorOfValue.push_back(6);
vectorOfValue.push_back(7);
vectorOfValue.push_back(8);
vectorOfValue.push_back(9);
vectorOfValue.push_back(10);
I would like to know how the program can print out the vectors of values bigger 3 and smaller than 9.
It is a set of the data to exclude the outliers for example.
If you want to use the standard library algorithms and iterators, you could use std::copy_if:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
auto main(int argc, char* argv[]) -> int
{
std::vector<int> vectorOfValue;
// code for initialization of vector ..
std::copy_if(vectorOfValue.begin(),
vectorOfValue.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[](const int value) { return value > 3 && value < 9; });
}
Short approach of mine using auto syntax instead of using iterator :
for(auto &i : vectorOfValue) {
if (i > 3 && i < 9) {
std::cout << i << std::endl;
}
}
I'm making a program that uses the std::generate_n function. I can get it to work fine with arrays, but I can't figure out how to make it work with a list container. Here is what I have:
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
int current = 0;
int UniqueNumber () { return ++current; }
int main ()
{
list<int> L;
list<int>::iterator it;
generate_n (L.begin(), 9, UniqueNumber);
cout << "list contains:";
for (it=L.begin(); it!=L.end(); ++it)
cout << ' ' << *it << '\n';
return 0;
}
The output only displays "list contains:" with nothing after that. I know my output loop functions correctly because I tried it manually with the insert() method, so the problem is something with the generate_n function. I think I'm passing the arguments wrong. Anyone know what I did?
You want to use an insert-iterator to add items to your list:
generate_n (back_inserter(L), 9, UniqueNumber);
Be sure to #include <iterator> to use it. Another possibility would be to use std::iota:
list<int> L(10);
std::iota(L.begin(), L.end(), 1);
Oh, and to display the contents of the list, you probably want:
std::copy(L.begin(), L.end(), ostream_iterator<int>(std::cout, "\n"));
or (in C++11):
for (auto i : L)
std::cout << ' ' << i << '\n';
generate_n doesn't insert, it just dereferences and assigns.
See the below possible implementation of generate_n (copied from here):
template< class OutputIt, class Size, class Generator >
OutputIt generate_n( OutputIt first, Size count, Generator g )
{
for( Size i = 0; i < count; i++ ) {
*first++ = g();
}
return first;
}
So you need to make sure the list is the appropriate size before you call it.
So, change:
list<int> L;
to:
list<int> L(9);
Let's say I have a std::vector and I get by some means the address of the n-th element.
Is there a simple way (faster than iterating through the vector) to get the index at which the element appears, given the base address of my std::vector? Let's assume I'm sure the element is in the vector.
Since you know the element is within the vector, and vector guarantees that its storage is contiguous, you could do:
index = element_pointer - vector.data();
or
index = element_pointer - &vector[0];
Note that technically the contiguous guarantee was introduced in C++03, but I haven't heard of a C++98 implementation that doesn't happen to follow it.
distance( xxx.begin(), theIterator);
The above will only work for a vector::iterator. If you only have a raw pointer to an element, you must use it this way:
distance(&v[0], theElementPtr);
Yes - because a vector guarantees all elements are in a contiguous block of memory you can use pointer arithmetic to find it like so
#include <iostream>
#include <vector>
int main(int argc, char *argv[])
{
std::vector<int> vec;
for(int i=0; i<10; ++i)
{
vec.push_back(i);
}
int *ptr=&vec[5];
int *front=&vec[0];
std::cout << "Your index=" << ptr-front << std::endl;
return 0;
}
On the way of learning, I have taken the following notes:
#include <iostream>
#include <vector>
int main() {
std::vector<std::string> words={"This","is","just","a","trial!"};
size_t i; //using the contiguous property of a vector:
for (auto const& elem : words) {
i = &elem - &*words.begin();// or
i = &elem - &words.front();// or
i = &elem - words.data();// or
i = std::addressof(elem) - std::addressof(words[0]);
if(std::addressof(elem) == &words.front())
std::cout << elem <<" (at"<<&elem<<") relative to ("<< &words[0] << ") takes position ##"<<i<< std::endl;
else std::cout << elem <<" (at"<<&elem<< ") takes position ##"<<i<< std::endl;
}
return 0;
}
Test run here.
It is open to further study (or learn from masters) which one is the most secured/safe and/or most efficient approach.