Why won't this array initialize? - c++

This is essentially what I'm trying to do, but not the actual source code.
namespace namespace {
int array [3];
}
namespace::array={1,2,3}
my gcc asks for an expression, and I'm not sure of what to do. Must I namespace::array[1]; each individual element?

You can only use an initializer list in a definition:
int array[3] = { 1, 2, 3 };
If you use:
int array[3];
then you need to initialize the array in a function, using
array[0] = 1;
array[1] = 2;
array[2] = 3;

Although it an odd mixture of C99 and C++, gcc allows this:
#include <string.h>
int a[3];
int main()
{
memcpy(a, (int[3]){ 1, 2, 3}, sizeof(a));
}
!

How about namespace ns { int array[3] = {1, 2, 3}; }?

There are several ways:
1) Explicitly set values for each element:
namespace ns {
int array [3];
}
ns::array[0]=1;
ns::array[1]=2;
ns::array[2]=3;
\\ or if they should contain consequtive values:
\\ for (size_t i = 0; i < 3; ++i)
\\ ns::array[i] = i + 1;
2) If you want initialize static array in place of its declaration, then you could move it initializer list as follows:
namespace ns {
int array[3] = {1, 2, 3};
}
3) Use typedef:
namespace ns {
typedef int array_t[3];
}
ns::array_t array = {1, 2, 3};
3) Also you can make some research of std::tr1::array, which may be used as such:
std::tr1::array<int, 3> arr = {1, 2, 3};

Related

A good way to construct a vector of 2d array

What I want to do is
double A[2][2] = {
{4, 7},
{2, 6}
};
std::vector<double[2][2]> B;
for (int i = 1; i <= 5; i++)
{
B.push_back(A);
}
But C++ cannot store an array in std::vector, what is the proper (speed) way to do that? Is A[2][2] faster than std::arraydue to cache coherency?
std::array is probably the best way to go here. It should preform nearly identically to the C style array you've got:
#include <array>
#include <vector>
int main() {
using Array2d = std::array<std::array<double, 2>, 2>;
Array2d A = {{{4, 7}, {2, 6}}};
std::vector<Array2d> B;
for (int i = 1; i <= 5; i++) {
B.push_back(A);
}
}

set multiple array variables at the same time (c++)

I'm trying to make an ASCII art using C++, and having some problems in arrays.
Is there any way to set multiple array variables at the same time?
Let me be more specific.
When you initialize an array, you can do this way.
int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
By the way shown above, you can set 10 array variables at the same time.
However, I want to (re) set some of the array variables like this?
a[1] = 3;
a[4] = 2;
a[5] = 2;
a[7] = 2;
Since there is NO rule in the variables, I can't do
for(int i=0; i<10; i++) a[i] = i+1;
fill(n);
I can't use an for statement or the fill, fill_n function, since there is no regularity.
To sum up,
Is there any way to set more than 1 array variables at the same time? (Like the second code snipplet above?
Given a index-value mapping list, and assign it one by one.
template<typename T, size_t N>
void Update(T(&arr)[N], const std::vector<std::pair<size_t, T>>& mappings)
{
for (const auto& mapping : mappings)
if(mapping.first < N)
arr[mapping.first] = arr[mapping.second];
}
int main()
{
int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Update(arr, { {1, 3}, {4, 2}, {5, 2}, {7, 2} });
return 0;
}
As far as I'm aware without a pattern a control structure is kind of redundant, you might be better served reading from a file.
// for user input
int arr[10] = { 0,1,2,3,4,5,6,7,8,9 };
for (int i = 0; i < 10; i++) {
cout << "Please input your value for array index " << i << endl;
cin >> arr[i];
}
// for manual input in initalization
int arr[10] = { 0, 3, 2, 2, 2, 5, 6, 7, 8, 9 };
However a better approach might be to read it from a file, http://www.cplusplus.com/forum/general/58945/ Read "TheMassiveChipmunk"'s post there for exactly how to do it.
Assuming you know which indices you will be changing upfront you can use a separate index array:
int ind[4]= {1,4,5,7};
..and an accompanying array with values
int new_val[4] = {3,2,2,2};
The you can use the following for loop to assign the values:
for (int i=0; i<4; i++)
arr[ind[i]] = new_val[i];
You should also use some variable signifying the number of indices to be changed like int val_num = 4 instead of plain number 4.
Changes that are defined in runtime to an array can be easily implemented by using a list to save tuples that represent the changes you want to make. As an example, we can write:
#include <tuple>
#include <list>
#include <iostream>
using namespace std;
typedef tuple <int, int> Change;
int main() {
int a[5] = {1,2,3,4,5};
list<Change> changes;
//represents changing the 2-th entry to 8.
Change change(2,8);
changes.push_back(change);
for(auto current_change: changes)
a[get<0>(current_change)] = get<1>(current_change);
cout << a[2] << '\n';
}
Prints 8.

How do you delete and append values to an array in c++?

I am a beginner in c++ and I am wondering how do you delete and append values to arrays.
What I mean is like this:
int arr[] = {1, 2, 3, 4}
I want to turn it into:
int arr[] = {1, 2, 3}
by deleting the last value of the array.
Also,
I would like to know how to append the a value to the end of an array. Like this:
int arr[] = {1, 2, 3, 4}
Into this:
int arr[] = {1, 2, 3, 4, 5}
Can anyone help me.
Thanks.
You can't, without new/delete, but std::vector is better. Here's an example of both.
#include <iostream>
#include <vector>
int main() {
// With new/delete:
int *array = new int[3];
array[0] = 1;
array[1] = 2;
array[2] = 3;
// `array` processing...
int *array2 = new int[4];
for (int i = 0; i < 3; i++) {
// copy old data into new array (array2)
array2[i] = array[i];
}
array2[3] = 4;
delete []array;
// `array2` processing...
delete []array2;
// With STL vector:
std::vector<int> array3;
array3.resize(3);
array3[0] = 1;
array3[1] = 2;
array3[2] = 3;
// `array3` processing...
// Add any number of elements
array3.push_back(4);
// resized `array3` processing...
return 0;
}

How do I stop my array from printing address?

I have a header, cpp and main class.
//Arr.h
class Arr
{
public:
void setArr();
void printArr();
private:
int x[5];
};
//Arr.cpp
#include "Arr.h"
#include <iostream>
using namespace std;
void Arr::setArr()
{
int x[5] = { 2, 3, 5, 7, 11 };
}
void Arr::printArr()
{
for (int i = 0; i < 5; i++)
{
cout << x[i] << "\n";
}
}
//main.cpp
int main()
{
Arr a;
a.setArr();
a.printArr();
}
However, when I run the code, a.printArr() prints out array address and not the values contained in the array. Is there a way to fix this?
Your code will print not address but some indeterminate value generated via default-initializing. Initialize the member array instead of the local array to throw away.
void Arr::setArr()
{
x[0] = 2;
x[1] = 3;
x[2] = 5;
x[3] = 7;
x[4] = 11;
}
Your problem is here:
void Arr::setArr()
{
int x[5] = { 2, 3, 5, 7, 11 };
}
the declaration int x[5] defines a new array of 5 elements which will be destroyed on exiting that function; and the name x hides the data member Arr::x.
One way you can do it is this:
void Arr::setArr()
{
/*static*/ auto arr = { 2, 3, 5, 7, 11 };
std::copy(arr.begin(), arr.end(), x);
}
Full code:
#include <iostream>
#include <algorithm>
class Arr
{
public:
void setArr();
void printArr();
private:
int x[5];
};
using namespace std;
void Arr::setArr()
{
/*static*/ auto arr = { 2, 3, 5, 7, 11 };
std::copy(arr.begin(), arr.end(), x);
}
void Arr::printArr()
{
for (int i = 0; i < 5; i++)
{
cout << x[i] << "\n";
}
}
//main.cpp
int main()
{
Arr a;
a.setArr();
a.printArr();
}
Your code is not printing array address. Maybe you saw some unexpected numbers and assumed it was an address, but in fact it is undefined behaviour caused by outputting uninitialized variables.
Your code int x[5] = .... failed because this declares a new local variable x, it doesn't modify the class member x.
Perhaps you tried:
x = { 2, 3, 5, 7, 11 };
and got compilation errors. This is because C-style arrays may not be assigned. This annoying rule is a hangover from C++'s past. To avoid this problem and many others, you can try to avoid using C-style arrays. In this case use a C++ array:
private:
std::array<int, 5> x;
Then the suggested assignment will work.
As WhiZTiM has already pointed out, your problem is at the setArr function in your class. The reason for this is because in C++ you cannot assign values to the array in the "normal fashion" i.e. using x = {blah, blah, blah}; (unless you use std::array<int, ARRAYSIZE>). In setArr you are creating another array named x and then this array is deleted once it is out of scope, and in printArr you are printing an array with no values in it yet.
Each value in the array must be set individually in C styled arrays (as shown in MikeCAT's answer).
One solution to this is to create a temporary array with the values you want and assigning the values to your class array through a for loop, i.e.:
void Arr::setArr() {
const int ARRAYSIZE = 5;
int tmp[ARRAYSIZE] = {2, 3, 5, 7, 11};
for (int i = 0; i < ARRAYSIZE; ++i) {
x[i] = tmp[i];
}
}
As M.M also pointed out, can simply change int x[5] in your private variables in Arr to std::array<int, 5> x and then in setArr simply have the statement: x = {2, 3, 5, 7, 11}; which is the better option in my opinion and easier to read, but it's also good to know how to use C arrays 😊

C/C++ arrays assignment

Sample code:
int ar[3];
............
ar[0] = 123;
ar[1] = 456;
ar[2] = 789;
Is there any way to init it shorter? Something like:
int ar[3];
............
ar[] = { 123, 456, 789 };
I don't need solution like:
int ar[] = { 123, 456, 789 };
Definition and initialization must be separate.
What you are asking for cannot be done directly. There are, however different things that you can do there, starting from creation of a local array initialized with the aggregate initialization and then memcpy-ed over your array (valid only for POD types), or using higher level libraries like boost::assign.
// option1
int array[10];
//... code
{
int tmp[10] = { 1, 2, 3, 4, 5 }
memcpy( array, tmp, sizeof array ); // ! beware of both array sizes here!!
} // end of local scope, tmp should go away and compiler can reclaim stack space
I don't have time to check how to do this with boost::assign, as I hardly ever work with raw arrays.
Arrays can be assigned directly:
int a[3] = {1, 2, 3};
Check the C++ Arrays tutorial, too.
int a[] = {1,2,3};
this doesn't work for you?
main()
{
int a[] = {1,3,2};
printf("%d %d %d\n", a[0], a[1], a[2]);
printf("Size: %d\n", (sizeof(a) / sizeof(int)));
}
prints:
1 3 2
Size: 3
What about the C99 array initialization?
int array[] = {
[0] = 5, // array[0] = 5
[3] = 8, // array[3] = 8
[255] = 9, // array[255] = 9
};
#include <iostream>
using namespace std;
int main()
{
int arr[3];
arr[0] = 123, arr[1] = 345, arr[2] = 567;
printf("%d,%d,%d", arr[0], arr[1], arr[2]);
return 0;
}