int *tthousand = new int[10000];
int *hthousand = new int[100000];
static int tmillion[10000000];
Hello there,
I'm trying to dynamically allocate memory for a series of arrays. These arrays are then populated with random numbers ranging from 0 to 10,000,000. From there, they are sorted using a quicksort/selection sort. The problem I'm running into is that whenever the "tmillion" array is reached, the program will run for a time and then a stack overflow occurs.
I've tried writing it as:
int *tmillion = new int[10000000];
and..
static int tmillion[10000000];
I must be missing something simple. Apologies, I'm still a bit new to C++.
Thoughts?
Just for future reference. Since C++11 std::array was introduced in Standard Library. It should be preferred than C-like built-in array.
Example:
#include <array>
std::array<int, 10000000> myArray;
// fill the array with data
std::sort(myArray.begin(); myArray.end()); // sorts data using default operator <
More information about this container can be found on Bjarne homepage: http://www.stroustrup.com/C++11FAQ.html#std-array
The standard container array is a fixed-sized random-access sequence of elements defined in . It has no space overheads beyond what it needs to hold its elements, it does not use free store, it can be initialized with an initializer list, it knows its size (number of elements), and doesn't convert to a pointer unless you explicitly ask it to. In other words, it is very much like a built-in array without the problems.
Additional example:
#include <array> // std::array
#include <algorithm> // std::sort
#include <iostream> // std::cout
int main()
{
std::array<int, 10> myArray = {8, 3, 6, 7}; // array with 10 elements but create it with declaring only first 4 elements
std::cout << "BEFORE SORT:" << std::endl;
for (const auto& element : myArray)
{
std::cout << element << std::endl;
}
std::sort(myArray.begin(), myArray.end()); // sorts data using default operator <
std::cout << "AFTER SORT:" << std::endl;
for (const auto& element : myArray)
{
std::cout << element << std::endl;
}
}
Output:
BEFORE SORT:
8
3
6
7
0
0
0
0
0
0
AFTER SORT:
0
0
0
0
0
0
3
6
7
8
Related
So here's a simple program that just search for two numbers in an array that sum up to a certain value k
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
unordered_set<int> hashtable;
int k =7;
int arr[5] = {1, 2, 3, 4, 5};
int s = sizeof(arr);
for (int i =0; i<s; i++){
if( hashtable.find(k - arr[i])!= hashtable.end() )
{
cout << arr[i] << endl;
cout<< "found one " << arr[i] << " and "<< k-arr[i]<< endl;
} else {
hashtable.insert(arr[i]);
}
}
return 0;
}
And here's the out put, I am getting
4
found one 4 and 3
5
found one 5 and 2
7
found one 7 and 0
7
found one 7 and 0
Am I missing something?
You access the array outside of its bounds. The behaviour of the program is undefined.
sizeof does not yield the number of elements in an array. It yields the size of an object in bytes. When the size of the element is more than one byte - and int is more than one byte on most systems - then the number of bytes in the array is more than the number of elements.
A correct way to get the number of elements in an array is to use std::size:
int s = std::size(arr);
Since you use only arr[i] and not i itself, you can write for (auto a : arr). This will respect the array bounds, you don't need to calculate the maximum index. Hence, it avoids the wrong calculation (which the other answers fix)
Maybe there are other ways to get the size of an array but for now this will do :
int s = sizeof(arr)/sizeof(arr[0]);
While taking a look at a solution for a problem, I came across this implementation of a vector.
const int MX = 100000;
std::vector <int> adj[MX];
The push_back() function doesn't work with this implementation of the vector class, and to add an element, the following code was used:
std::ifstream fin ("file.in");
int N = 5;
for (int i = 0; i < (N-1); i++) {
int A,B; fin >> A >> B; // reading values from another file
adj[A].pb(B), adj[B].pb(A);
}
The way this code is adding is adding pushing back a value to a certain part of the list, which I imagine as a vector inside the vector of the form:
{
{ },
{ }
}
In addition, how would I loop through this vector because for (int n : adj) does not work. I am not sure what the form of this vector is because this method of looping does not work.
What you have is C style array of vectors, off the bat you could replace that with std::array:
std::array<std::vector<int>, MX> adj;
To loop through these you would have to use a nested one, the outer loop to go through the array, and the inner one to go through each vector, something like this:
const int MX = 3;
//array of 3 vectors
std::array<std::vector<int>, MX> adj {{{1,2,3,4}, {5,6,7,8}, {9, 10, 11, 12}}};
for(auto &v : adj){ //for the array
for(auto i : v){ //for each vector
std::cout << i << " ";
}
std::cout << "\n";
}
Output:
1 2 3 4
5 6 7 8
9 10 11 12
You can also access individual elements using C style indexing:
std::cout << adj[1][0]; // vector element index 0 of array index 1
Or in a safer way, using container member at:
std::cout << adj.at(1).at(0);
This would output 5.
You should be careful though, when randomly filling the array, an array is not meant to have empty elements, otherwise the loops will go through uninitialized array members, which is not ideal, perhaps you are looking for some other kind of container.
char mychars[] = { 'A','B','C','D' };
vector<int> a(mychars, mychars + 4);
cout << a[0] << " " << a[1] << " " << a[2] << " " << a[3];
why it's output is
65 66 67 68 ?
i have created vector of int so it should have stored A,B,C,D in one int of 4 bytes but it is storing them individually by creating 4 ints why ?
No. a vector does not know the internal representation of the contained object. When you construct a vector using the range constructor, it will only constructs a container with as many elements as the range [first,last), with each element emplace-constructed from its corresponding element in myChars array, in the same order.
When you pass an array of chars to the constructor, the constructor assumes that the array contains chars and hence loops through the array, casts each char to an integer and creates the vector from the integers.
I guess you could do a little "hack" with pointers in order to achieve
the desired result. Instead of passing a pointer to char to the vector constructor,
you can cast mychars to an integer pointer so that c++ views the 4 bytes consumed
by mychars array as a single integer.
However, you should be careful about the size of the supposed integer array that is used as offset to the constructor.
In your case, the offset is 1 instead of 4, because for every 4 chars you have 1 integer. However, I replaced it with the more general sizeof(mychars)/sizeof(int)) in order to account for arrays with more than 4 elements (the elements of mychar must be a multiple of 4).
#include <iostream>
#include <vector>
using namespace std;
/*
Id is between 0 and 3 (inclusive)
*/
char char_from_int(int number, int id) {
return (number >> (8*id)) & 0xff;
}
int main()
{
char mychars[] = { 'A','B','C','D','e','f','g','h' };
vector<int> a((int*)mychars, (int*)mychars +sizeof(mychars)/sizeof(int));
for(int i=0;i<a.size();i++) {
cout<<char_from_int(a[i],0)<<char_from_int(a[i],1)<<char_from_int(a[i],2)<<char_from_int(a[i],3)<<endl;
}
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a[5];
for (int i = -1; i < 7; i++)
cout << i << " " << setw(2) << a[i] << endl;
}
So I'm trying to figure out why this won't work. If i take out a[i] it works, but if i leave it in, the for loop goes from -2 until the 1000's which is obviously not right. Is it because a[i] is not bound to the parameters of the for loop (i < 7)? I'm not really sure I understand.
EDIT As many of you have explained it was a matter of uninitializing the array and using bounds outside of the array (e.g -2). It was not something I thought of, nor found when searching for why this was happening.
First, as marcadian pointed out, the array a is not initialized, so values in the array are completely random.
Also, the size of the a array is 5, meaning that you can access between indexes 0 and 4 inclusive.
However, in your loop, you try to access at index -1, and index 6. Attempting to write and read at invalid indexes ( such as -1 and 6, in this case ) is undefinded behavior ( it can crash with a segmentation fault, or corrupt other variables, which can make debugging process very hard ... )
A way to avoid buffer overrun like you did is to use std::array STL container, like this :
std::array<int, 5> a;
//Access elements using the method 'at()', it has bound checking
a.at(0); // 0 is a valid index
//a.at(-1); // -1 is not a valid index, it will crash ( at least in debug mode )
//a.at(6); // 6 is also not a valid index
The std::array STL container does the same things normal array does, but provides useful methods
You're printing out random value in memory because variable a is not initialized. Uninitialized variable has random value in memory. What are you trying to do?
in computers an array is really just a given number of values, starting at array[0], and ending at array[n].
int a[5]; statically allocates space for 5 integers on the stack, starting at a[0], and ending at a[4].
Try this iteration instead:
for (int i = 0; i < 4; i++)
In addition to not initializing the array, a, the indices you would be using to access its elements are out of bounds. C++ uses zero-indexing - you could try, for instance:
int main() {
int a[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
cout << i << " " << a[i] << endl;
}
}
Output would be:
0 1
1 2
2 3
3 4
4 5
#include <iostream>
#include <vector>
int main()
{
static const unsigned TOTAL = 4;
std::vector<int> v[TOTAL];
v[2].push_back(37);
//std::cout << v.size(); error
std::cout << v[0].size();
std::cout << v[2].size();
return 0;
}
Is is valid to instatnitate std::vector with bracket like in the code above?
MSVS and ideone compile it just fine, but vector is messed up (see error line).
I know I can use resize, but what is going on here?
You are creating a TOTAL sized array of vectors.
What you need is
std::vector<int> v(TOTAL);
This constructs a vector with TOTAL zero-initialized ints.
Then,
std::cout << v.size() << std::endl; // prints 4
std::cout << v[0] << std::endl; // prints 0
and so on.
It is valid to instantiate std::vector with bracket like in the code, but with different meanings.
std::vector<int> v[TOTAL];
Here you defined a vector v of size=TOTAL, each element of which is a vector<int>. Initially, these TOTAL vector<int>s are all empty (i.e. size=0).
After you call v[2].push_back(37);, v[2] will become a vector<int> of size=1 with a value 37 in it.
So the output you for the following will be 0 and 1.
std::cout << v[0].size();
std::cout << v[2].size();
If you want to call size(), you should call v[i].size() or define it as vector<int> v(TOTAL); (v is a vector of size=TOTAL, each element of which is an int).
I know I can use resize, but what is going on here?
you are basicly creating an array of type std::vector<int>, just as in here:
int arr[TOTAL];
Is is valid to instatnitate std::vector with bracket like in the code above?
you can have an array of vectors, but from your post it is not what you are after.
If you want to give your vector some initial size then use
std::vector<int> v(TOTAL);
this will set initial size of your vector to TOTAL, and value initialize all elements (set them to zero).
But you might actually want to:
std::vector<int> v;
v.reserve(TOTAL); // this is not necessary
// v.size() is zero here, push_back will add elements starting from index 0
because in case of std::vector<int> v(TOTAL); your push_back will start adding from index TOTAL.