I want to have a mini function that allows the user to type a group of numbers, and each of them will be dynamically allocated into an array. For example:
int main()
{
int* x = NULL;
int n, numbers;
std::cin >> n;
x = new int[n]
for (int i=0;i<n;i++){
std::cin >> numbers;
x[i] = numbers;
}
delete [] x;
So when the user types in
3
The user will be able to type in 3 numbers following that
3 1 2 3
I am trying to store the values 1, 2, 3 into an array so it will look like
[1, 2, 3]
but right now it's storing as
[123]
Anyway i can fix this? I'm new to C++ programming so I feel like there's an easy solution to this but i'm not sure how.. thank you!
You could store each element of the array directly into x[i]. Not sure what numbers is used for (I've assigned numbers from x[i]).
x is the array that is to be deleted. And there is a missing ; at x = new int[x] - is that a typo?
int main()
{
int* x = NULL;
int n, numbers;
std::cin >> n;
x = new int[n];
for (int i=0;i<n;i++){
std::cin >> x[i];
numbers = x[i];
}
delete [] x;
You can use a vector instead:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v;
for (int i = 0; i < n; ++i)
{
int val;
cin >> val;
v.push_back(val);
}
}
C++'s vector takes care of memory allocation for you. You could then simply traverse it and print its contents.
cout << "[";
for (int i = 0; i < v.size(); ++i)
{
if (i != 0)
cout << ",";
cout << v[i];
}
cout << "]";
Example 1
int main()
{
int* x = NULL;
int n, numbers;
std::cin >> n;
x = new int[n]; // need a semi-colon here
for (int i=0;i<n;i++)
{
std::cin >> numbers;
x[i] = numbers;
}
for (int j = 0; j < n; ++j)
{
std::cout << "x[" << j << "] = " << x[j] << std::endl;
}
delete [] x; // you mean x, not a
return 0;
}
Once you fix (what I assume are just typos), what you have works fine. However, unless this is for an assignment, you should consider using std::vector instead of raw dynamic memory allocation. Doing so would reduce your code to about 4 lines.
int main()
{
std::vector<int> myvector;
std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), std::back_inserter(myvector));
std::copy(myvector.begin(), myvector.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
or, in C++11
int main()
{
std::vector<int> myvector{std::istream_iterator<int>(std::cin), std::istream_iterator<int>()};
std::copy(myvector.begin(), myvector.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
Why not just create the array dynamically? This way, the user won't have to type in the number of elements in advance:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
int x;
while (cin >> x)
vec.push_back(x);
for (int y: vec)
cout << y << ' ';
cout << '\n';
}
The cout statements are just to illustrate that everything worked.
Related
I have some code written but I'm not sure why the reversed array is not giving me the exact values I need. I created a second array the same size as the first and used nested for loops to fill the second with the contents of the first in reverse.
See below:
#include <iostream>
using namespace std;
int main()
{
// Ask for how big the array is
int n;
cout << "how big is the array?" << endl;
cin >> n;
// create array
int a[n];
// create second array
int b[n];
// ask for contents of the 1st array
cout << "what's in the array?" << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
// reverse the array
for (int i = n - 1; i >= 0; i--)
{
for (int k = 0; k < n; k++)
{
b[k] = a[i];
break;
}
}
// print out the new array
for (int k = 0; k < n; k++)
{
cout << b[k] << endl;
}
return 0;
}
you don't need 2 bucles for fill the second array
try with:
//reverse the array
s = 0;
for (int i=n-1;i>=0;i--){
b[n]=a[s];
s++;
}
Try something like this:
#include <algorithm>
#include <iostream>
#include <vector>
namespace {
template <typename IStream>
[[nodiscard]] int readOneIntFrom(IStream& istream) {
int x;
istream >> x;
return x;
}
}
int main()
{
// Ask for how big the array is
std::cout << "how big is the array?" << std::endl;
auto n = readOneIntFrom(std::cin);
// create array
std::vector<int> a;
// ask for contents of the 1st array
std::cout << "what's in the array?" << std::endl;
for (int i = 0; i < n; i++)
{
a.emplace_back(readOneIntFrom(std::cin)); // Make a new entry at the end of a.
}
// Construct b from a backward. (Or do auto b = a; std::reverse(b.begin(), b.end());
auto b = std::vector<int>(a.rbegin(), a.rend());
// print out the new array
for (const auto& bi : b)
{
std::cout << bi << std::endl;
}
return 0;
}
// Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
vector<int> printNonRepeated(int arr[], int n);
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
vector<int> v;
v = printNonRepeated(arr, n);
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
cout << endl;
}
return 0;
}
// } Driver Code Ends
// Function to print the non repeated elements in the array
// arr[]: input array
// n: size of array
vector<int> printNonRepeated(int arr[], int n) {
vector<int> a;
unordered_map<int, int> h;
int count = 0;
int i;
for (i = 0; i < n; i++) {
h[arr[i]]++;
}
int j = 0;
for (auto x : h) {
if (x.second == 1) {
a[j] = x.first;
j++;
}
}
return a;
}
I want to print the nonrepeating numbers using the function vector<int> printNonRepeated(int arr[],int n). I am trying using hashmap. I am getting segmentation error while compiling. Where am I doing a mistake.
I do not have the permission to change the main function. I can only change the 'printNonRepeated' function.
a[j] = x.first;
j++;
You can't access the jth index of a without having allocated space first. The size of the array needs to be predefined, or you can use push_back so that the vector adds a new element to the end.
a.push_back(x.first);
For starters variable length arrays as this
int n;
cin >> n;
int arr[n];
is not a standard C++ feature.
You may not use the subscript operator with an empty vector.
vector<int> a;
//...
for (auto x : h) {
if (x.second == 1) {
a[j] = x.first;
j++;
}
Creating vectors is redundant. You could initially store entered values in a container of the type std::map declared in main.
int b, c, d;
cin >>b>>c>>d;
int **a[b];
for(int i=0;i<b;++i){
*a[i]=new int[c];
for(int j=0;j<c;j++){
a[i][j]=new int[d];
}
}
I would like to create a 3 dimension int.I think the problem is when I create the second dimension it is not a pointer and I can not create a 3th on it.
As #yacsha posted, you're better off using <vector> from the STL, rather than using raw pointers and new (or even pointers at all).
But, if creating a '3 dimension int' is really what you want, then you must declare your variables properly, allocate, then delete them:
#include <iostream>
int main()
{
int b, c, d;
std::cin >> b >> c >> d;
// declaring a variable to a pointer that points to a pointer ... etc.
// really hard to maintain and read
int*** a = new int**[b];
for (int i = 0; i < b; ++i) {
a[i] = new int*[c];
for (int j = 0; j < c; j++) {
a[i][j] = new int[d];
for (int k = 0; k < d; k++)
std::cin >> a[i][j][k];
}
}
// using it like a normal 3d array would be used
for (int i = 0; i < b; i++) {
for (int j = 0; j < c; j++) {
for (int k = 0; k < d; k++)
std::cout << a[i][j][k] << ' ';
std::cout << '\n';
}
std::cout << '\n';
}
// deleting is necessary after using them
for (int i = 0; i < b; i++)
for (int j = 0; j < c; j++)
delete[] a[i][j];
for (int i = 0; i < b; i++)
delete[] a[i];
delete[] a;
}
As you can see, this is a nightmare to maintain. It's much more easier to use <vector> because the container takes care of the memory allocation for you. If you don't want to use STL, atleast use a[b][c][d], where b, c, d are const / constexpr.
This is how it looks like with <vector>:
#include <iostream>
#include <vector>
int main()
{
int b, c, d;
std::cin >> b >> c >> d;
std::vector<std::vector<std::vector<int>>> threeDim(b, std::vector<std::vector<int>>(c, std::vector<int>(d, 0)));
for (const auto x : threeDim) {
for (const auto y : x) {
for (const auto z : y)
std::cout << z << ' ';
std::cout << '\n';
}
std::cout << '\n';
}
}
You could typedef / using to shorten std::vector if you find it too cumbersome to declare and init the 3d array, or you could resize it via loops.
You can declare a as a ***a[b] (pointer, to a pointer, to a pointer).
int ***a[b];
I suggest using the standard stl, which is safer than using pointers, so I would have to declare the "vector template":
#include <vector>
using std::vector;
The code would look like:
vector<vector<vector<int>>> A;
int b, c, d;
cin >>b>>c>>d;
int i,j,k;
A.resize(b);
for(i=0;i<b;++i){
A[i].resize(c);
for(j=0;j<c;j++){
A[i][j].resize(d);
for(k=0;k<d;k++){
// Optional inputs elements
cout << "Input element " <<i<<","<<j<<","<<k<<": ";
cin >> A[i][j][k];
}
}
}
I need to create 2 arrays, each with 4 elements. One array contains four int values gotten from the user, and the other array contains pointers to the elements of the first array. I keep getting the following error:
array type 'int *[4]' is not assignable
on this line:
my_ptrs = &my_ints;
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int my_ints[4];
int *my_ptrs[4];
float temp;
int num;
for (int x=0; x< 4; x++)
{
cout << "Enter Integer:" << endl;
cin >> num;
my_ints[x] = num;
}
my_ptrs = &my_ints;
for(int k=0; k<=3; k++)
{
for(int j=k+1; j<=3; j++)
{
if(my_ptrs[k]>my_ptrs[j])
{
temp=*my_ptrs[k];
my_ptrs[k]=my_ptrs[j];
*my_ptrs[j]=temp;
}
}
cout << my_ptrs[k] << " ";
}
return 0;
}
Your apparent intent is to have each pointer in my_ptrs to point to the corresponding value in my_ints.
I'm afraid there are no shortcuts here, using a single assignment. You have to do it the hard way:
for (int i=0; i<4; ++i)
my_ptrs[i]=&my_ints[i];
You cannot assign a pointer-to-an-array to an array variable, like you are trying to do. But what you can do instead is either:
initialize the second array in its declaration directly:
int my_ints[4];
int* my_ptrs[4] = {&my_ints[0], &my_ints[1], &my_ints[2], &my_ints[3]};
populate the array in a separate loop:
int my_ints[4];
int* my_ptrs[4];
for (int i = 0; i < 4; ++i)
my_ptrs[i] = &my_ints[i];
That being said, based on what you are trying to do ("i want to print the my_ptrs array in ascending order"), you could just get rid of the second array altogether and use the std::sort() algorithm instead:
Sorts the elements in the range [first, last) in ascending order.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int my_ints[4];
for (int x = 0; x < 4; ++x)
{
cout << "Enter Integer:" << endl;
cin >> my_ints[x];
}
std::sort(my_ints, my_ints+4);
for(int k = 0; k < 4; ++k)
cout << my_ints[k] << " ";
return 0;
}
The idea of the program is to input elements in an array. Then give the integer 'x' a value. If 'x' is 3 and the array a[] holds the elements {1,2,3,4,5,6}, we must "split" a[] into two other arrays. Lets say b[] and c[].
In b[] we must put all values lower or equal to 3 and in c[] all values greater than 3.
My question is- How can i express the 3 elements in b[i]?
#include <iostream>
using namespace std;
int main()
{
int a[6];
int b[6];
int c[6];
int d;
for (int i = 0; i < 6; i++) {
cin >> a[i];
}
cin >> d;
for (int i = 0; i < 6; i++) {
if (d >= a[i]) {
b[i] = a[i]; // if d is 3, then i have 3 elements. How can i express them?
}
}
for (int i = 0; i < 6; i++) {
if (d< a[i]) {
c[i] = a[i];
}
}
for (int i = 0; i < 3; i++) {
cout << b[i];
}
cout << endl;
for (int i = 3; i < 6; i++) {
cout << c[i];
}
return 0;
}
I think all you're trying to do is have a way to determine how many int values you're copying from a[] to either b[] or c[]. To do that, introduce two more counters that start at zero and increment with each item copied to the associated array:
Something like this:
#include <iostream>
using namespace std;
int main()
{
int a[6];
int b[6], b_count=0; // see here
int c[6], c_count=0; // see here
int d;
for (int i = 0; i < 6; i++) {
cin >> a[i];
}
cin >> d;
for (int i = 0; i < 6; i++) {
if (d >= a[i]) {
b[b_count++] = a[i]; // see here
}
}
for (int i = 0; i < 6; i++) {
if (d< a[i]) {
c[c_count++] = a[i]; // see here
}
}
for (int i = 0; i < b_count; i++) { // see here
cout << b[i];
}
cout << endl;
for (int i = 3; i < c_count; i++) { // and finally here
cout << c[i];
}
return 0;
}
Now, if you want b[] or c[] to be dynamic in their space allocation, then dynamic-managed containers like st::vector<> would be useful, but I don't think that is required for this specific task. Your b[] and c[] are already large enough to hold all elements from a[] if needed.
WhozCraigs answer does a good job showing what you need to solve this using traditional arrays according to your tasks requirements.
I'd just like to show you how this can be done if you were allowed the full arsenal of the standard library. It is why people are calling for you to use std::vector. Things gets simpler that way.
#include <algorithm>
#include <iostream>
int main()
{
int a[6] = {1, 2, 3, 4, 5, 6 }; // Not using input for brevity.
int x = 3; // No input, for brevity
// Lets use the std:: instead of primitives
auto first_part = std::begin(a);
auto last = std::end(a);
auto comparison = [x](int e){ return e <= x; };
auto second_part = std::partition(first_part, last, comparison);
// Print the second part.
std::for_each(second_part, last, [](int e){ std::cout << e; });
// The first part is first_part -> second_part
}
The partition function does exactly what your problem is asking you to solve, but it does it inside of the array a. The returned value is the first element in the second part.
use std::vectors. do not use int[]s.
with int[]s (that are pre-c++11) you could, with a few heavy assumptions, find array length with sizeof(X)/sizeof(X[0]); This has, however, never been a good practice.
in the example you provided, probably you wanted to:
#define MAX_LEN 100
...
int main() {
int a[MAX_LEN];
int b[MAX_LEN];
int c[MAX_LEN];
int n;
std::cout << "how many elements do you want to read?" << std::endl;
std::cin >> n;
and use n from there on (these are common practice in programming schools)
Consider a function that reads a vector of ints:
std::vector<int> readVector() {
int n;
std::cout << "how many elements do you want to read?" << std::endl;
std::cin >> n;
std::vector<int> ret;
for (int i=0; i<n; i++) {
std::cout << "please enter element " << (i+1) << std::endl;
int el;
std::cin >> el;
ret.push_back(el);
}
return ret;
}
you could use, in main, auto a = readVector(); auto b = readVector(); a.size() would be the length, and would allow to keep any number of ints
Here's an example of how you'll approach it once you've a little more experience.
Anything you don't understand in here is worth studying here:
#include <iostream>
#include <vector>
#include <utility>
std::vector<int> get_inputs(std::istream& is)
{
std::vector<int> result;
int i;
while(result.size() < 6 && is >> i) {
result.push_back(i);
}
return result;
}
std::pair<std::vector<int>, std::vector<int>>
split_vector(const std::vector<int>& src, int target)
{
auto it = std::find(src.begin(), src.end(), target);
if (it != src.end()) {
std::advance(it, 1);
}
return std::make_pair(std::vector<int>(src.begin(), it),
std::vector<int>(it, src.end()));
}
void print_vector(const std::vector<int>& vec)
{
auto sep = " ";
std::cout << "[";
for (auto i : vec) {
std::cout << sep << i;
sep = ", ";
}
std::cout << " ]" << std::endl;
}
int main()
{
auto initial_vector = get_inputs(std::cin);
int pivot;
if(std::cin >> pivot)
{
auto results = split_vector(initial_vector, pivot);
print_vector(results.first);
print_vector(results.second);
}
else
{
std::cerr << "not enough data";
return 1;
}
return 0;
}
example input:
1 2 3 4 5 6
3
expected output:
[ 1, 2, 3 ]
[ 4, 5, 6 ]