How do you print a full array of values in C++ - c++

I'm trying to figure out print a full array in C++.
For example, I want the output to be x = [1,2,3,4,5....n]
How would I go about doing this? I already know how to print each element of the array using a simple for loop. For example in python, you could simply say x = [], make a for loop to append elements to the array, and print x.
So let's say I have this code.
int n = 10;
int m = 10;
double x[n];
// Generate vector of random values for x
for (int i = 0; i<n; ++i)
{
x[i] = (double)rand()/(double)RAND_MAX;
// Print each array element
// std::cout << x[i] << std::endl;
}
std::cout << x[n-1] << std::endl;
This obviously only spits out x[10] in this case. Where as I want x = [1...n] etc.
What is the simplest way of achieving this?
I'm using Eclipse on OSX. I use the g++ compiler that the Xcode developer tools has for the command line

You're looking for a range based for loop:
double x[] = { .0, .1, .2, .3, .4 };
// Iterate through all elements
for (auto d : x)
{
std::cout << d << std::endl;
}
Note that the above takes a copy of each element, so if you wanted to modify an element you'd need to use
for (auto& d : x)
instead.
Alternatively you could just use a normal for loop like you did originally:
for (int i = 0; i<n; ++i)
{
std::cout << x[i] << std::endl;
}
The range based for loop is the easiest though.

if you know something about STL , you can try to use iterator
code:
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
int arr[5] = {1,2,3,4,5};
copy(arr, arr + sizeof(arr)/sizeof(int),ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}

Related

Easy way to iterate through multiple std::vectors in C++

I have two std::vectors of same type, and I need to iterate through both of them using the same routine. Something like this:
std::vector<int> values1, values2;
int counter = 0;
for (int val : values1) counter += val;
for (int val : values2) counter += val;
Is there any simple way to write the last two lines in a single loop, to avoid code repetition? Something that would look like this:
std::vector<int> values1, values2;
int counter = 0;
for (int val : values1, values2) counter += val;
If you don't need to access either vector after iterating over them, you could move them into a std::initializer_list and then iterate over that:
std::vector<int> values1{1, 2, 3};
std::vector<int> values2{4, 5, 6};
for (const auto& v : {std::move(values1), std::move(values2)}) {
for (auto value : v) {
std::cout << value << ' ';
}
}
// prints "1 2 3 4 5 6 "
As ShadowRanger pointed out below, moving from the original vectors isn't necessary if we instead iterate over an initializer list of std::reference_wrappers. This can be done by swapping std::move with std::cref (or std::ref if you need to mutate them):
for (const auto& v : {std::cref(values1), std::cref(values2)}) {
for (auto value : v.get()) {
std::cout << value << ' ';
}
}
// prints "1 2 3 4 5 6 ", as before
No, there isn't, sorry. At least not directly in the language.
Boost can do it:
for (int val : boost::range::join(values1, values2))
counter += val;
Because Boost can do it, you could make something to do it as well, by making an iterator type of your own that casts a "view" over both collections.
But, particularly in the simple case you've shown, it's often not worth it. If your loop body is more complex, I recommend hiving it off into a function that takes int. This can just be a lambda declared immediately above the loop. That's what I do.
With range-v3 you could write:
namespace rs = ranges;
namespace rv = ranges::views;
int counter = rs::accumulate(rv::concat(values1, values2), 0);
I suspect there will be library support for this by C++23 (or C++2b). All that is needed is a range adaptor views::concat, and the range-ification of the <numeric> header.
How about:
std::vector<int> values_vecs[2];
// ...
int counter = 0;
for (const auto& values : values_vecs)
for (int val : values) counter += val;
It's not exactly the same as your original code, however it can support easily more than 2 vectors.
In case the vectors are there already as two separate vectors, you can still go with:
std::vector<int> values1, values2;
//...
int counter = 0;
for (auto values_ptr : {&values1, &values2})
for (int val : *values_ptr) counter += val;
I used something like this to iterate through 3 different vectors of different size where one vector was dependent of the two other vectors (first_vector is dependent on the other vectors).
#include <iostream>
#include <vector>
int main() {
std::vector<int> first_vector{50, 20, 30, 5000};
std::vector<int> second_vector{10};
std::vector<int> third_vector{500, 10};
for (int i = 0, j = 0, k = 0; i < first_vector.size(); ++i, ++j, ++k) {
if (j == second_vector.size()) {
j = 0;
}
if (k == third_vector.size()) {
k = 0;
}
std::cout << first_vector[i] << '|' << second_vector[j] << '|'
<< third_vector[k] << '\n';
std::cin.get();
}
return 0;
}

C++ pointers and for loops

I just started using c ++. I am trying to run a forward Euler, where I use a for loop and pointers. But I don't understand what's wrong?
#include <iostream>
using namespace std;
void euler(){
int n = 10;
double dt = 0.1;
double *a=new double[n];
double *v=new double[n];
double *t = new double[n];
int vr = 5;
for (int i=0;i<n; i++){
a[i+1] = vr + i;
v[i+1] = v[i] + a[i+1]*dt;
t[i+1] = t[i] + dt;
}
cout << v << endl;
}
int main(int argc, char const *argv[]) {
euler();
return 0;
}
The terminal gives me this "0x7fce7cc017d0"
You are printing out the pointer itself, instead of the value to which it is pointing. Try one of these:
cout << *v << endl;
or
for (int i=0;i<n; i++)
cout << v[i] << endl;
Also, as mentioned in a commment, no need for the +1 in your array indexing. By the way, this is not a good use of pointers in C++. In general, you don't want to use pointers unless you really need to. With code as simple as yours, you can simply declare arrays.
double *v=new double[n];
...
cout << v << endl;
V is a pointer to an array of n doubles.
When you are printing you are printing the value of the pointer.
Which is why you get results like "0x7fce7cc017d0" because that's the value of the pointer.
If you want to print out the values of the array you must index into it properly.
std::cout << v[0] << "\n"
You can make your original code print the content of vector v if you implement operator << for vecotor, for example like here:
Overloading output stream operator for vector<T>

Segmentation fault: 11; range-based for loop

I'm working on a small programming exercise in C++. Goal is to initiate an array with the first 32 exponentations of 2 and to output them afterwards.
Using a normal for loop there's no problem but I tried to use the range-based for loop introduced in the C++11 standard.
During compilation I get the warning "range-based for loop is a C++11 extension [-Wc++11-extensions]".
Running the program I get the error "Segmentation fault: 11" without any further output.
I got already that the elem variable somehow is broken but I don't know how.
Hope you can help a n00b :)
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int LAENGE = 32;
long potenzen[LAENGE];
for(int elem : potenzen)
{
potenzen[elem] = pow(2.0, (double) (elem + 1));
}
for(int elem : potenzen)
{
cout << endl;
cout << potenzen[elem];
}
cout << endl;
return 0;
}
elem is assigned the values in potenzen, not indices. cout << elem; is what you want instead to print the elements of the array. And in order to fill the array, simply use integer indices:
for (int i = 0; i < LENGTH; i++) { // ProTip #1: use English identifiers
array[i] = 2 << i; // ProTip #2: don't use `pow()` when working with integers
}
As to the compiler warning: use the -std=c++11 or -std=c++0x flag when compiling to tell the compiler you are intending to use C++11 features (assuming you use GCC or clang -- I'm not sure about other compilers.)
Ranged for loop wil give you element values, and not the element indices.
potenzen[elem] = pow(2.0, (double) (elem + 1));
should be
for(int i = 0; i < LAENGE; i++)
potenzen[i] = 2 << i;
(For shifting, refer to the H2CO3's answer and to the his comments below)
Note that you can't use foreach loop here:
for(int& elem : potenzen)
{
elem = pow(2.0, (double) (elem + 1));
}
as you're accessing not-initialized value of elem in the right side of the statement.
Also:
for(int elem : potenzen)
{
cout << endl;
cout << potenzen[elem];
}
Should be
for(int elem : potenzen)
{
cout << endl;
cout << elem;
}
as elem will contain array values.
The above answers rightly point out the issues in your code, however if you want to have array indices as element values you've to set them up, without which they'd be initialized to indeterminate (garbage) values; the following code is also a solution that's somewhat similar to what you tried to do:
#include <iostream>
#include <algorithm>
int main()
{
constexpr auto count = 32;
unsigned long long values[count] = { }; // initialise elements to 0
auto i = 0;
// fill them with their respective index values
std::generate_n(values, count, [&i] { return i++; });
for(auto &x : values)
{
// without casting the literal 2 would be treated as an int
x = static_cast<unsigned long long>(2) << x;
std::cout << x << std::endl;
}
return 0;
}
I've used unsigned long long instead of long, since on many systems the size of a long is 4 bytes, but 2^32 = 4294967296 = 0x100000000 I.e. 33 bits are required. Also since we know that all values are going to be positive, making it unsigned makes more sense.

C++ Element access is failing to work?

this is a super simple question but I cannot seem to see what has gone wrong. What this code does is it counts the number of elements in the pixID vector and returns that sum to a diagonal element in the square matrix PtP. However even though 'i' in the first loop reads: 0,5,10,15 for the elements the output looks like this:
1,0,0,0,
0,0,3,0,
0,0,0,0,
0,3,0,0,
instead of the desired:
1,0,0,0,
0,3,0,0,
0,0,2,0,
0,0,0,2,
Any idea what is going on here?
double where(std::vector<double> &vec,unsigned int &v){
double count = 0;
int val;
for(std::vector<double>::iterator it = vec.begin();
it != vec.end();
++it){
if(*it == val){
count++;
}
}
return count;
}
int main(){
unsigned int pixSide = 2;
int id;
std::vector<double> pixID {1,1,2,3,0,2,1,3};
std::vector<double> PtP (pixSide*pixSide);
for(unsigned int i=0;i<pixSide*pixSide;i++){
id = i*pixSide*pixSide + i;
std::cout << id << std::endl;
PtP[id] = where(pixID,i);
}
for(int i=0;i<pixSide*pixSide;i++){
for(int j=0;j<pixSide*pixSide;j++){
std::cout << int(PtP[i*pixSide + j]) << ',';
if(j==pixSide*pixSide-1){
std::cout << std::endl;
}
}
}
}
First, you're not using the parameter "v" in where(). Instead, you're using the uninitialized local variable "val".
Second, I think you may be confusing the dimensions of your objects at a few points. I think you're getting confused about whether you're keeping just the diagonal or the whole matrix.
This way you will consistently be keeping the whole matrix:
std::vector<double> PtP (pixSide*pixSide);
should be
std::vector<double> PtP (pixSide*pixSide*pixSide*pixSide);
and
std::cout << int(PtP[i*pixSide + j]) << ',';
should be
std::cout << int(PtP[i*pixSide*pixSide + j]) << ',';
Of course, this is wasteful for such a sparse matrix -- I don't know whether that matters in your application (are your real numbers larger than pixSide=2?).

C++ Program Apparently Printing Memory Address instead of Array

#include <iostream>
using namespace std;
int main(){
int findMax(int *);
const int MAX = 100;
int values[MAX];
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
char *helper;
// Clean input array and transfer it to values.
for(int i = 0; i < (MAX) && ivals[i] != 0; i++){
helper = ivals[i * 2];
values[i] = atoi(helper);
}
int mval = findMax(values);
cout << values << endl << mval;
return 0;
}
//Function to find the maximum value in the array
int findMax(int arr[]){
int localmax = 0;
for(int i = 0; i < (sizeof(arr)/sizeof(int)); i++){
if(arr[i] > localmax){
localmax = arr[i];
}
}
return localmax;
}
The purpose of this program is for the user to input a space-separated series of values ended by a 0. That array is then to be analyzed to find the max. I figured out how to convert what is originally a char[] into an int[] so that I can use the findMax() function on it without error but the sorting loop seems to have a problem of its own and when "cout << values << endl << mval;" is called, it returns only a memory address instead of what should be a non-spaced sequence of ints. Can anybody explain what I am doing wrong? It seems that I may have made some mistake using the pointers but I cannot figure out what.
Printing values won't print the contents of the array as you expect, it will print the memory location of the first element of the array.
Try something like this instead:
#include <iterator>
#include <algorithm>
// ...
copy(&values[0], &values[MAX], ostream_iterator(cout, " "));
Sorry I can't post actual working code, but your original post is a mess with many syntax and syntactic errors.
EDIT: In the interest of being more complete and more approachable & understandable to beginners, I've written a small program that illustrates 4 ways to accomplish this.
Method 1 uses copy with an ostream_iterator as I've done above.
Method 2 below is probably the most basic & easiest to understand.
Method 3 is a C++0x method. I know the question is tagged C++, but I thought it might be educational to add this.
Method 4 is a C++ approach using a vector and for_each. I've implemented a functor that does the dumping.
Share & Enjoy
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
struct dump_val : public unary_function<int,void>
{
void operator()(int val)
{
cout << val << " ";
}
};
int main(){
int vals[5] = {1,2,3,4,5};
// version 1, using std::copy and ostream_iterator
copy(&vals[0], &vals[5], ostream_iterator<int>(cout, " "));
cout << endl;
// version 2, using a simple hand-written loop
for( size_t i = 0; i < 5; ++i )
cout << vals[i] << " ";
cout << endl;
// version 3, using C++0x lambdas
for_each(&vals[0], &vals[5], [](int val)
{
cout << val << " ";
}
);
cout << endl;
// version 4, with elements in a vector and calling a functor from for_each
vector<int> vals_vec;
vals_vec.push_back(1);
vals_vec.push_back(2);
vals_vec.push_back(3);
vals_vec.push_back(4);
vals_vec.push_back(5);
for_each( vals_vec.begin(), vals_vec.end(), dump_val() );
cout << endl;
}
When you pass around an array of X it's really a pointer to an array of X that you're passing around. So when you pass values to cout it only has the pointer to print out.
You really should look into using some of the standard algorithms to make your life simpler.
For example to print all the elements in an array you can just write
std::copy(values, values+MAX, std::ostream_iterator<int>(std::cout, "\n"));
To find the max element you could just write
int mval = *std::max_element(values, values+MAX);
So your code becomes
#include <iostream>
using namespace std;
int main(){
const int MAX = 100;
int values[MAX];
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
char *helper;
// Clean input array and transfer it to values.
for(int i = 0; i < (MAX) && ivals[i] != 0; i++){
helper = ivals[i * 2];
values[i] = atoi(helper);
}
copy(values, values+MAX, ostream_iterator<int>(cout, "\n"));
cout << *std::max_element(values, values+MAX);
return 0;
}
Doing this removes the need for your findMax method altogether.
I'd also re-write your code so that you use a vector instead of an array. This makes your code even shorter. And you can use stringstream to convert strings to numbers.
Something like this should work and is a lot less code than the original.
int main(){
vector<int> values;
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
int temp = 0;
stringstream ss(ivals);
//read the next int out of the stream and put it in temp
while(ss >> temp) {
//add temp to the vector of ints
values.push_back(temp);
}
copy(values.begin(), values.end(), ostream_iterator<int>(cout, "\n"));
cout << *std::max_element(values.begin(), values.end());
return 0;
}
Array of int is promoted to a pointer to int when passed to a function. There is no operator << taking ordinary array. If you want to use operator << this way, you need to use std::vector instead.
Note: it is possible technically to distinguish array when passed to a function using template, but this is not implemented for standard operator <<.
for(int i = 0; i < (sizeof(arr)/sizeof(int)); i++){
sizeof(arr) here is the size of the pointer to the array. C++ will not pass the actual array, that would be grossly inefficient. You'd typically only get one pass through the loop. Declare your function like this:
int findMax(int* arr, size_t elements) {
//...
}
But, really, use a vector.
Oh, hang on, the question. Loop through the array and print each individual element.