im tryin to reverse an array using pointer which is a class member:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class my_string
{
char* ptr;
int size;
public:
my_string(){};
my_string(char* str) : ptr(str),size(strlen(ptr)){};
char* getstr () {return ptr;};
void reverse();
int find (char);
void print();
};
void my_string::reverse()
{
int size2=size;
for (int i=0;i<(size/2);i++)
{
char tmp=ptr[i];
ptr[i]=ptr[size2-1];
ptr[size2-1]=ptr[i];
size2--;
}
}
int my_string::find(char c)
{
for (int i=0;i<size;i++)
{
if (ptr[i]==c)
return i;
}
return -1;
}
void my_string::print()
{
for (int i=0;i<size;i++)
cout<<ptr[i];
cout<<endl;
}
int main()
{
my_string s1("abcde");
s1.print();
s1.reverse();
s1.print();
}
im not gettin any errors but the reverse function is surely not working.
can someone please explain to me why?
*this is an homework assignment asking me not to use dynamic allocation or strings (for now).
You didn't mention not being able to use standard library algorithms, so
std::reverse(ptr, ptr+size);
You can use standard algorithm std::reverse declared in header <algorithm>.
For example
std::reverse( ptr, ptr + size );
But if you want to do it yourself then the function could look the following way
void my_string::reverse()
{
for ( int i = 0; i < size/2; i++ )
{
char tmp = ptr[i];
ptr[i] = ptr[size-1-i];
ptr[size-1-i] = tmp;
}
}
A test program
#include <iostream>
#include <cstring>
int main()
{
char s[] = "123456789";
char *ptr = s;
int size = std::strlen( ptr );
std::cout << s << std::endl;
for ( int i = 0; i < size/2; i++ )
{
char tmp = ptr[i];
ptr[i] = ptr[size-1-i];
ptr[size-1-i] = tmp;
}
std::cout << s << std::endl;
}
Output is
123456789
987654321
Related
I'm working on an assignment to create a class called StringBuilder that is used for fast string concatenation. I'm supposed to store strings in a dynamic array and have methods such as Append(string) which adds a new string to the dynamic array. The method I'm currently struggling with is GetString() that creates a single string on the heap that is the length of all the strings in the dynamic array that have been added thus far.
the code I have so far is:
okay my main problem is my GetString() function prints out hello over and over again until I force quit the program in Xcode. I don't understand what inside that method is making that happen.
My header file:
#pragma once
#include <string>
using namespace std;
class StringBuilder
{
public:
StringBuilder();
//~StringBuilder();
void GetString();
void AppendAll(string*, int);
void Length();
void Clear();
void Append(string userString);
void DoubleArray(string*& allWords, int newCapacity);
private:
string* p_array;
int capacity = 5;
};
my .cpp file :
#include "StringBuilder.hpp"
#include <iostream>
#include <string>
using namespace std;
----------
void StringBuilder::Append(string userString)
{
int nextWordPosition = 0;
for(int i=0; i < capacity ; i++)
{
p_array[i] = userString;
cout << p_array[i] << endl;
nextWordPosition +=1;
if(capacity == nextWordPosition)
{
capacity *=2;
DoubleArray(p_array, capacity * 2);
}
}
nextWordPosition++;
}
void StringBuilder::DoubleArray(string*& allWords, int newCapacity)
{
string* p_temp = new string[newCapacity];
for(int i =0; i < newCapacity / 2; i++)
{
p_temp[i] = allWords[i];
}
delete[] allWords;
allWords = p_temp;
}
void StringBuilder:: GetString()
{
for(int i=0; i < capacity ; i++)
{
cout << p_array[i]<< endl;
}
}
my main.cpp file :
#include <iostream>
#include <string>
#include "StringBuilder.hpp"
using namespace std;
int main()
{
string testString = "hello";
string test = "world!";
StringBuilder Builder1;
Builder1.Append(testString);
Builder1.Append(test);
Builder1.GetString();
return 0;
}
This question already has an answer here:
Initializing an std::array of non-default-constructible elements?
(1 answer)
Closed 2 years ago.
I want to initialize a array of 1 million objects on stack, I need to write one million &i in the following code.
Is there any other good way.
#include <iostream>
class A{
public:
A(int* p)
: p_(p){
std::cout << "A" << std::endl;
}
private:
int *p_;
};
int main(){
int i;
A a[3] = {&i, &i, &i};
}
#include <iostream>
#include <type_traits>
class A{
public:
A(int* p)
: p_(p){
std::cout << "A" << std::endl;
}
private:
int *p_;
};
int main(){
using elemType = std::aligned_storage<sizeof(A), alignof(A)>::type;
const size_t count = 1000000;
int i;
elemType a[count];
for(int idx = 0; idx < count: ++idx) {
new (&a[idx]) A(&i);
}
...
for(int idx = 0; idx < count: ++idx) {
reinterpret_cast<A&>(a[idx]).~A();
}
return 0;
}
C++ new operator can be used to call constructor on a preallocated memory:
#include <iostream>
#include <cstddef>
#include <cstdint>
class A{
public:
A(int* p)
: p_(p){
std::cout << "A" << std::endl;
}
private:
int *p_;
};
int main(){
int i;
uint8_t buf[1000000 * sizeof(A)];
A* pa = reinterpret_cast<A*>(buf);
for (size_t n = 0; n < 1000000; n++) {
new (&pa[n]) A(&i);
}
return 0;
}
You could use std::vector and initialize is with a million elements
std::vector<A> a(1000000, &i);
I know there is something wrong with the class member functions because I comment everything in them out and the program will run fine but when I uncomment anything it stops working. The constructor runs fine as well.
Here is my CharArray.h file:
#ifndef CHARARRAY_H
#define CHARARRAY_H
class CharArray
{
private:
char * pArray;
int iSize;
public:
CharArray(int size)
{
char *pArray = nullptr;
iSize = size;
pArray = new char[iSize];
pArray = '\0';
}
void setItem (int loc, char ch);
char getItem (int loc);
~CharArray()
{
delete [] pArray;
}
};
#endif // CHARARRAY_H
Here is my member functions:
#include <iostream>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include "CharArray.h"
using namespace std;
void CharArray::setItem (int loc, char ch)
{
pArray[loc] = ch;
cout << pArray[loc] << endl;
return;
}
char CharArray::getItem (int loc)
{
char c;
c = pArray[loc];
return c;
}
And here is my main file:
#include <iostream>
#include <iomanip>
#include "CharArray.h"
using namespace std;
int main()
{
CharArray myChar (5);
int size;
char cstr[10] = "Drew";
myChar.setItem(1, 'A');
char c = myChar.getItem(5);
cout << c << endl;
return 0;
}
Your first problem is in the constructor:
CharArray(int size)
{
char *pArray = nullptr; // <-- unrelated to the pArray in the object!
iSize = size;
pArray = new char[iSize];
pArray = '\0'; // <-- we just lost the handle to new array
}
That last line should instead be:
*pArray = '\0';
Also, it would be better to use a more modern constructor style such as this:
CharArray(int size)
: pArray(new char[size]),
iSize(size)
{
*pArray = '\0';
}
#include <stdio.h>
#include <iostream>
using namespace std;
//char* b[6] = new char[6];
char a[6] = {'b','c','d','e','f','g'};
char c[6] = {'a','b','d','d','f','g'};
int main()
{
char d[][6]={*a,*c};
for (int x = 0 ; x < 1; x++)
{
for(int y = 0; y<6; y++)
{
char test = d[x][y];
cout << test <<"\n";
}
}
return 0;
}
This code is C++ code. I am trying to create a class where it stores the char array. Then there is another char array of array storing already declared char variables. It compiles fine but it doesn't work out to as it should. It doesn't get me the right value that it should when the program tries to print the value
May be you meant array of pointers:
char *d[]={a,c};
typedef std::vector<char> VectorChar;
typedef std::vector< VectorChar* > VectorVectorChar;
struct V
{
V() : _v{ '0', '1', '2' } {}
VectorChar _v;
};
int main(void)
{
V arrV[5];
VectorVectorChar vvc;
for ( auto& v : arrV )
vvc.push_back( &v._v );
// print them
for ( auto pV : vvc )
{
for ( auto c : *pV )
cout << c << ' ';
cout << '\n;
}
return 0;
}
what i understood from the question that, you want to create class to store char array, which already initialized.
#include <stdio.h>
#include <iostream>
char a[6] = {'b','c','d','e','f','g'}; // Initialized character array. MAX 6
// This class will hold char array
class Test {
public:
void setName(char *name);
const char* getName();
private:
char m_name[6]; // MAX 6 ( since you already initialized(MAX 6), So no need dynamic memory allocation. )
};
void Test::setName(char *name) {
strcpy(m_name, name); // Copy, already initialized array
}
const char* Test::getName() {
return m_name;
}
int main(int argc, char** argv) {
{
Test foobar;
foobar.setName( a ); // set the pointer which point to starting of the initialized array.
cout << foobar.getName();
return 0;
}
char a[6] = {'b','c','d','e','f','\0'};
char c[6] = {'a','b','d','d','f','\0'};
char* d[]= {a,c};
for (int x = 0 ; x < 2; x++)
{
for(int y = 0; y < 6; y++)
{
char test = d[x][y];
cout << test << "\n";
}
}
return 0;
It seems the attribute test aisbn is successfully storing the data invoking setCode(), setDigit(). But The trouble starts failing while I attempt these values to store into list<test> simul
The list attribute takes the value of digit after setDigit() but the code. How can I put both code and digit into the list attribute? I can't see where the problem is. The code:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <list>
using namespace std;
class test
{
private:
string code;
int digit;
public:
//constructor
test(): code(""), digit(0) { }
//copy constructor
test(const test &other):
digit(other.digit)
{
for(unsigned int i=0; i < code.length(); i++)
code[i] = other.code[i];
}
//set up the private values
void setCode(const string &temp, const int num);
void setCode(const string &temp);
void setDigit(const int &num);
//return the value of the pointer character
const string &getCode() const;
const unsigned int getDigit() const;
};
const string& test::getCode() const
{
return code;
}
const unsigned int test::getDigit() const
{
return digit;
}
void test::setCode(const string &temp, const int num)
{
if((int)code.size() <= num)
{
code.resize(num+1);
}
code[num] = temp[num];
}
void test::setCode(const string &temp)
{
code = temp;
}
void test::setDigit(const int &num)
{
digit = num;
}
int main()
{
const string contents = "dfskr-123";
test aisbn;
list<test> simul;
list<test>::iterator testitr;
testitr = simul.begin();
int count = 0;
cout << contents << '\n';
for(int i=0; i < (int)contents.length(); i++)
{
aisbn.setCode(contents);
aisbn.setDigit(count+1);
simul.push_back(aisbn);
count++;
}
cout << contents << '\n';
/*for(; testitr !=simul.end(); simul++)
{
cout << testitr->getCode() << "\n";
}*/
}
It looks like you are having issues with your for loop, you need to modify your for loop like so:
for(testitr = simul.begin(); testitr !=simul.end(); testitr++)
^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^
although, push_back does not invalidate iterators for std::list I think it is more readable to set the iterator where you are using it. Based on your response you also need to modify the copy constructor:
test(const test &other): code(other.code), digit(other.digit) {}
^^^^^^^^^^^^^^^^
how about using the vector
std::vector<test> simul;
for(int i=0; i < (int)contents.length(); i++)
{
aisbn.setCode(contents);
aisbn.setDigit(count+1);
simul.push_back(aisbn);
count++;
}
iterators, pointers and references related to the container are invalidated.
Otherwise, only the last iterator is invalidated.