Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to make the elements of an array accessible, but I've had no success so far. This is the code, and I've created it due to the given assignment.
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
class Matrix_1D
{
private:
int *p2values;
int num_elements;
public:
Matrix_1D(int *p2v, int n); // CTOR
~Matrix_1D(); // DTOR
void show();
};
Matrix_1D::Matrix_1D(int *p2v, int n)
{
n = sizeof(p2v)/sizeof(int); // the problem comes from the fact that sizeof(p2v) = 4 bytes, and not the length of the entire array!!!
num_elements = n;
p2values = new int [n];
for(int i = 0; i<num_elements; i++)
p2values[i] = p2v[i];
}
Matrix_1D::~Matrix_1D()
{
delete [] p2values;
}
void Matrix_1D::show()
{
for(int i=0; i<num_elements; i++)
cout << p2values[i] << endl;
}
int main()
{
int array_a[] = {5,3,5};
Matrix_1D fkt_1D_a(array_a, sizeof(array_a)/sizeof(int));
fkt_1D_a.show();
system("pause");
return 0;
}
Matrix_1D::Matrix_1D(int *p2v, int n)
{
n = sizeof(p2v)/sizeof(int); // the problem comes from the fact that sizeof(p2v) = 4 bytes, and not the length of the entire array!!!
num_elements = n;
p2values = new int [n];
for(int i = 0; i<num_elements; i++)
p2values[i] = p2v[i];
}
As you state the sizeof p2v is the size of the pointer so you have no idea how large the array is. Instead, use the parameter that is passed in and don't overwrite it:
Matrix_1D::Matrix_1D(int *p2v, int n)
{
// you don't need the first line at all.
num_elements = n;
p2values = new int [n];
for(int i = 0; i<num_elements; i++)
p2values[i] = p2v[i];
}
The proper C++ way to get the size of your int array is to use a template:
template <typename T, size_t N>
size_t size(T (&)[N]) {
return N; // size of array
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am doing c++ 6th edition the 6th exercise of 8th chapter. I have questions on this template. I don't know why it always shows the last string not shows the string that has the max length.
#include <iostream>
#include <cstring>
//8.6
using namespace std;
template <typename T> T Maxn(T *,int);
template <> char * Maxn<>(char **,int );
int main()
{
double arr_1[5] = { 0.0,3.0,1.0,4.0,5.0 };
cout << "double max: " << Maxn(arr_1,5) << endl;
int arr_2[4] = { 3,4,1,0 };
cout << "int max: " << Maxn(arr_2, 4) << endl;
const char *arr_3[4] = { "sdf","tttq","ttttrrsdss" ,"q12221"};
cout << "char max:" << Maxn(arr_3, 4) << endl;
return 0;
}
template <typename T>
T Maxn(T *p,int n)
{
T max = p[0];
for (int i = 0; i < n; i++)
{
if (p[i] > max)
max = p[i];
}
return max;
}
template <> char * Maxn<>(char **p, int n)
{
char * max = p[0];
for (int i = 0; i < n; i++)
{
if (strlen(p[i]) > strlen(max))
{
max = p[i];
}
}
return max;
}
You should simply start using a debugger or at minimum you could visit your code by using printf debugging. You will see, that your char* specialization is never used!
Reason:
Your data type for the "strings" is const char* which matches better for the first template than to your specialization and so simply the first template version is called. And this compares now the address of the strings. If your compiler puts the strings in the order presented in the source, you will always see the last string as result, as it has the highest address.
Simply use:
template <> const char * Maxn<>(const char **p, int n)
{
const char * max = p[0];
for (int i = 0; i < n; i++)
{
if (strlen(p[i]) > strlen(max))
{
max = p[i];
}
}
return max;
}
BTW: Your code has some efficiency flows. You compare in the first step two times the same value which is not needed.
Type of arr_3 is const char *, but not char *:
const char *arr_3[4] = { "sdf","tttq","ttttrrsdss" ,"q12221"};
, so the first implementation of Maxn is called, where strlen is not used.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
in this code i try to divide the a[5] into two arrays on the criterion of stored data in the array .......
and store the index of the array a[5] to other arrays to show these index contain different data elements
but i doesn't work for me
#include <iostream>
using namespace std;
void printarray(int b[], int count)
{
int i;
for(i=0;i<count;i++)
cout<<b[i]<<endl;
}
void main()
{
int a[5]={1,0,0,1,1};
int array[5][5]=
{
{0,5,0,4,0},
{0,0,6,0,7},
{0,0,0,0,8},
{0,0,0,0,10},
{0,0,0,0,0}
};
int count=0;
int counti=0;
int C1=0;
int i;
for(i=0;i<5;i++)
{
if(C1==a[i])
{
count++;
}
else
{
counti++;
}
}
int *b= new int[count];
int *c= new int[counti];
for(i=0;i<5;i++)
{
if(C1==a[i])
{
b[i]=i;
}
else
{
c[i]=i;
}
}
printarray(b,count);
}
the code display the grabage values... plz help me
its show the following result
-842151450
1
The first i was 1 , so b will contain {1, 2}. where ( b[1] = 1, b[2] = 2 )
when you loop through b to print all elements you start from index 0 although b started from index 1.
you can fix index using (j, k instead of i).
int *b = new int[count];
int *c = new int[counti];
int j, k;
j = k = 0;
for (i = 0; i<5; i++)
{
if (C1 == a[i])
{
b[j++] = i;
}
else
{
c[k++] = i;
}
}
printarray(b, count);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
header
#ifndef INTVECTOR_H
#define INTVECTOR_H
using namespace std;
class IntVector{
private:
unsigned sz;
unsigned cap;
int *data;
public:
IntVector();
IntVector(unsigned size);
IntVector(unsigned size, int value);
unsigned size() const;
};
#endif
Body
#include "IntVector.h"
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
IntVector::IntVector(){
sz = 0;
cap = 0;
data = NULL;
}
IntVector::IntVector(unsigned size){
sz = size;
cap = size;
data = new int[sz];
*data = 0;
}
IntVector::IntVector(unsigned size, int value){
sz = size;
cap = size;
data = new int[sz];
for(unsigned int i = 0; i < sz; i++){
data[i] = value;
}
}
unsigned IntVector::size() const{
return sz;
}
When I test my functions in Main, (IntVector(6, 4);
cout << testing.size() << endl;), my testing.size() test consistently outputs 0 when it should theoretically be 6 as I assign sz and cap in the IntVector functions. Any ideas on why it is outputting 0?
Looks like you're creating a temporary which is discarded here:
IntVector(6, 4);
You want to create an object, like so:
IntVector testing(6, 4);
Then it works.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was testing one of my classes, but for some reason I can't seem to cast an intiger from a 2d array to double. Here is my (very simplified) code:
In main.cpp
#include<iostream>
#include<conio.h>
#include<string>
#include "trajectories.h"
int main()
{
std::string response;
int numOfCoords;
int speed;
int ** coords;
std::cout<<"enter the number of coordinates: ";
std::cin>>numOfCoords;
std::cout<<"enter speed: ";
std::cin>>speed;
coords=new int *[numOfCoords];
for (int i=0; i<numOfCoords; i++)
coords[i] = new int[2];
for(int i=0; i<numOfCoords*2; i++)
{
if(i%2==0)
std::cout<<"enter point "<<i/2<<".x : ";
else
std::cout<<"enter point "<<i/2<<".y : ";
std::cin>>coords[i/2][i%2];
}
NPCTrajectory traj(numOfCoords, speed);
traj.AddCoordinates(coords);
std::cout<<coords[0][0]<<", "<<coords[0][1]<<std::endl;
getch();
double currentCoords[2];
currentCoords[0]=double(coords[0][0]);
currentCoords[1]=double(coords[0][1]);
for(;;)
{
traj.HandleEvents(currentCoords);
std::cout<<"current coordinates : ("<<currentCoords[0]<<", "<<currentCoords[1]<<")"<<std::endl;
std::cout<<"do you wish to continue? ";
getch();
}
}
Trajectories.h contains class declaration only, so I believe it is irrelevant. Here is my trajectories.cpp
#include "trajectories.h"
int FPSCap=5;
NPCTrajectory::NPCTrajectory(int npoints, int newSpeed)
{
numOfPoints=npoints;
this->speed=newSpeed;
points = new int * [npoints];
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
state = 0;
maxOffset=speed/FPSCap;
}
void NPCTrajectory::AddCoordinates(int ** coordinates)
{
for(int i=0;i<this->numOfPoints; i++)
{
points[i][0]=coordinates[i][0];
points[i][1]=coordinates[i][1];
}
}
void NPCTrajectory::HandleEvents(double (¤tCoordinates)[2])
{
if(state+1==numOfPoints) return;
if(Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1])<maxOffset) state++;
double ratio = maxOffset/Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1]);
currentCoordinates[0]+=(points[state+1][0]-currentCoordinates[0])*ratio;
currentCoordinates[1]+=(points[state+1][1]-currentCoordinates[1])*ratio;
}
Please note that removing command traj.AddCoordinates(coords) will make the problem disappear. Am I passing the array correctly to the function?
The problem is in your constructor NPCTrajectory. Replace npoints with loop variable i. The following code:
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
should be like:
for (int i=0; i<npoints; i++)
points[i] = new int[2];
Because of this incorrect allocation, you are getting error (segmentation fault) in AddCoordinates function when you try to access points[i][0] with i=0 (assuming you are giving npoints>0 in NPCTrajectory).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can I get the dValues[] in the line double dValues[] = {what should i input here?}?Because I'm using an array. The goal is to get the mode.
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
double GetMode(double daArray[], int iSize) {
// Allocate an int array of the same size to hold the
// repetition count
int* ipRepetition = new int[iSize];
for (int i = 0; i < iSize; ++i) {
ipRepetition[i] = 0;
int j = 0;
bool bFound = false;
while ((j < i) && (daArray[i] != daArray[j])) {
if (daArray[i] != daArray[j]) {
++j;
}
}
++(ipRepetition[j]);
}
int iMaxRepeat = 0;
for (int i = 1; i < iSize; ++i) {
if (ipRepetition[i] > ipRepetition[iMaxRepeat]) {
iMaxRepeat = i;
}
}
delete [] ipRepetition;
return daArray[iMaxRepeat];
}
int main()
{
int count, minusElements;
float newcount, twocount;
cout << "Enter Elements:";
std::cin >> count;
std::vector<float> number(count);
cout << "Enter " << count << " number:\n";
for(int i=0; i< count ;i++)
{
std::cin >> number[i];
}
double dValues[] = {};
int iArraySize = count;
std::cout << "Mode = "
<< GetMode(dValues, iArraySize) << std::endl;
You already have all the values in your number vector, but if you wanted to copy those values into a new array called dValues, you have to allocate it on the heap (since you don't know the size at compile-time), copy the elements from the vector, and later free up that memory:
double *dValues = new double[number.size()];
for (size_t i = 0; i < number.size(); i++)
{
dValues[i] = number[i];
}
// whatever you need to do with dValues
delete [] dValues;
You're also not checking that you're within the bounds of your vector in the for loop. A safer implementation would use the push_back() method on the vector rather than assigning the values by index.
If I understood you correctly, you wish to copy the elements from the vector to array. If yes -
float *dValues = new float[count] ; // Need to delete[] when done
std::copy( number.begin(), number.end(), dValues );
std::copy is in algorithms header. But why do you want to use/create raw array for this task. You already have the vector number and just pass it to GetMode(..)