Comparison behavior of ' <' operator - c++

Why is this printing "Popescu" instead of "Ionescu", since "Popescu" > "Ionescu"?
#include <iostream>
using namespace std;
int main(){
char v[3][100] = {"Popescu","Ionescu","Vasilescu"};
if(v[0]<v[1]){
cout << v[0];
}else{
cout << v[1];
}
return 0;
}

Since char[100] doesn't have an operator<, you fall back to operator< for char*. That was not what you intended - it returns the first object in memory. And v[0] definitely precedes v[1].
You want std::string, where operator< is overloaded to do what you want.

Your Initialization is wrong that is why print 'Popescu'
First You need to clear about your array position that is main criteria before start work on your program see my image
see below example:
char always take one character:
#include <iostream>
using namespace std;
int main(){
char v[3][3] =
{
{'p','I','l'},
{'s','e','r'},
{'q','w','x'}
};
cout<< v[0][0]; //print the array2d
return 0;
}
output:
p
First Condition:
#include <iostream>
using namespace std;
int main(){
char v[3][100] = {"p","I","l"};
if(v[0][0]==v[0][0])
{
//cout << v[0]; //when uncomment this line output is p
cout << v[1]; **see here print the i because check the position of array image**
}
else
{
cout << v[1];
}
return 0;
}
output: I //now the position of your array see below
Now the second Condition:
int main(){
char v[3][100] = {"p","I","l"};
if(v[1]==v[1])
{
// cout << v[0];
cout << v[1];
}
else
{
cout << v[1];
}
return 0;
output:
I
If the above criteria Understood then Come To your main problem:
#include <iostream>
using namespace std;
int main(){
char v[3][100] = {"p","I","l"};
if(v[0]<=v[1])
{
cout << v[0];
// cout << v[2];
}
else
{
cout << v[1];
}
return 0;
}
output: p
I hope my answer is understood.

Related

C++ - Checking if a word is palindrome in struct data type

I want to know how to check if a word is palindrome in struct data type or object whatever you want to call it. I want to read a data from file then I need to check if that type of word that I have read is a palindrome or not. Also i need to reverse order of the words but I did that so do not need any help about that.
Here is the code:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
struct lettersStr
{
string name;
string object;
};
int main(int argc, char** argv)
{
ifstream letter;
letter.open("letter.txt");
lettersStr things[200];
int numberOfThings= 0;
while(letter >> letter[numberOfThings].name >> letter[numberOfThings].object)
{
numberOfThings++;
}
for (int i = 0; i < numberOfThings; i++)
{
cout << letter[i].name << " " << letter[i].object<< endl;
}
string names;
for (int i = 0; i < numberOfThings; i++)
{
names= things[i].name;
}
for (int i = numberOfThings- 1; i >= 0; i--)
{
cout << things[i].name << endl;
}
bool x = true;
int j = names.length() - 1;
for (int i = 0; i < j; i++,j--)
{
if (things[i].name.at(i) != things[i].name.at(j))
x = false;
if (x)
{
cout << "String is a palindrome ";
}
else
cout << "String is not a palindrome";
}
And here is the cout:
Kayak Audi
Ahmed Golf7
Ahmed
Kayak
String is not a palindrome
String is not a palindrome
I think major problem is this:
for (int i = 0; i < j; i++,j--)
{
if (things[i].name.at(i) != things[i].name.at(j))
x = false;
As you can see it wont cout right way of checking if a word is palindrome or not.
P.S: If this is a stupid question I am sorry, I am a beginner in C++ programming.
Cheers
As already pointed out in the comments, for (int i = 0; i < j; i++,j--) loops though things and the letters of their names simultaneously. You also have to account for cases where you compare a lower and an upper case letter such as the 'K' and 'k' at the beginning and end of 'Kayak'. You can use std::tolower for this.
Here is an example (live demo):
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
bool is_palindrome(std::string name)
{
if (name.empty())
return false;
// As has been pointed out, you can also use std::equal.
// However, this is closer to your original approach.
for (unsigned int i = 0, j = name.length()-1; i < j; i++,j--)
{
if (std::tolower(name.at(i)) != std::tolower(name.at(j)))
return false;
}
return true;
}
struct lettersStr
{
string name;
string object;
};
int main(int argc, char** argv)
{
std::vector<lettersStr> vec = {lettersStr{"Kayak","Boat"},lettersStr{"Audi","Car"}};
for (const auto &obj : vec)
if (is_palindrome(obj.name))
std::cout << obj.name << " is a palindrome" << std::endl;
else
std::cout << obj.name << " isn't a palindrome" << std::endl;
}
It gives the output:
Kayak is a palindrome
Audi isn't a palindrome

Lowercasing Capital Letters in char array[] in C++ through Pointers

I am trying to use pointers to recursively lowercase all capital letters
using the C++ programming language. Below is the code snippet:
// Example program
#include <iostream>
#include <string>
using namespace std;
void all_lower(char* input) {
if ( *input ) {
cout << input << endl;
return;
}
if ( *input >= 'A' && *input <= 'Z') {
*input += 32; // convert capital letter to lowercase
}
cout << *input << endl;
all_lower(++input); // simply move to next char in array
}
int main() {
char test[] = "Test";
all_lower(test);
return 0;
}
The output ends up being:
"Test"
even though I tried to increase the ASCII code value of the element by 32.
You are exiting the function on the first non-null character detected, which is 'T', and then you output the entire array before exiting, so you are seeing the original unmodified input. You are not recursing through the array at all. You need to recurse through the array until you reach the null terminator.
You need to change this:
if ( *input ) {
cout << input << endl;
return;
}
To this instead:
if ( *input == 0 ) {
return;
}
Then the function will work as expected.
That being said, I suggest you remove the cout statements from the function, and do a single cout in main() after the function has exited. This will speed up the function, and prove that the content of the test[] array is actually being modified:
#include <iostream>
using namespace std;
void all_lower(char* input)
{
if ( *input == 0 ) {
return;
}
if ( *input >= 'A' && *input <= 'Z') {
*input += 32; // convert capital letter to lowercase
}
all_lower(++input); // simply move to next char in array
}
int main()
{
char test[] = "TEST";
cout << "Before: " << test << endl;
all_lower(test);
cout << "After: " << test << endl;
return 0;
}
Live Demo
And, since you are using C++, consider removing all_lower() altogether and use the STL std::transform() algorithm instead:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
char test[] = "TEST";
cout << "Before: " << test << endl;
transform(test, test+4, test, [](char ch){ return tolower(ch); });
cout << "After: " << test << endl;
return 0;
}
Live Demo
Something short and easy:
#include <iostream>
#include <string>
using namespace std;
void all_lower(const char* input) {
if (!*input) {
std::cout << std::endl;
return;
}
std::cout << (char)(std::isalpha(*input) ? tolower(*input) : *input);
all_lower(++input); // simply move to next char in array
}
int main() {
all_lower("Test");
return 0;
}

Heap Corruption at class destructor?

I've been trying to figure this out for hours now, and I'm at my wit's end. I would surely appreciate it if someone could tell me when I'm doing wrong.
I wrote a c++ code with class implementing a simple stack, trying to push and pop random stream of characters. It seems to work fine, but at the end of the file, it produces some sort of runtime error:
HEAP CORRUPTION DETECTED: after Normal block....
Since the error occurs at the end of the file, my guess is that there is a problem at deleting the pointer(class destructor). However, I have no idea what is wrong with the destructor I wrote.
Also, after some trial and error, I found out that if I address a bigger number to unsigned integer value iter1 (ex: 80), the runtime error does not occur. Could you explain what is the problem here, and how to bypass it?
stack.h:
class sstack
{
public:
sstack(int length = 256);
~sstack(void);
int sstackPop(char &c);
int sstackPush(char c);
bool isempty();
bool isFull();
protected:
private:
char *sstackBuffer;
int sstackSize;
int sstackIndex; // Initial = -1
};
stack.cpp:
#include "stack.h"
#include <iostream>
using namespace std;
sstack::sstack(int length)
{
sstackIndex = -1;
if (length > 0)
sstackSize = length;
else
sstackSize = 256;
sstackBuffer = new char[sstackSize];
}
sstack::~sstack(void)
{
delete[] sstackBuffer;
}
bool sstack::isempty()
{
if (sstackIndex < 0)
{
cout << "is empty!(isempty)" << endl;
return 1;
}
else
return 0;
}
bool sstack::isFull()
{
if (sstackIndex >= sstackSize)
return 1;
else
return 0;
}
int sstack::sstackPop(char &c)
{
if (!isempty())
{
c = sstackBuffer[sstackIndex--];
cout << sstackIndex << endl;
return 1;
}
else
{
cout << "is empty!(sstackPop)" << endl;
return 0;
}
}
int sstack::sstackPush(char c)
{
if (!isFull())
{
sstackBuffer[++sstackIndex] = c;
return 1;
}
else{
return 0;
}
}
main.cpp:
#include <iostream>
#include "stack.h"
#include <string>
using namespace std;
int main(){
unsigned int iter1 = 5;
unsigned int iter2 = 800;
sstack stackDefault;
sstack stack1(iter1);
sstack stack2(iter2);
char buffer[80];
memset(buffer, 0x00, 80);
char BUFFER[80] = "A random stream of characters";
strcpy_s(buffer, 80, BUFFER);
for (int i = 0; i< strlen(buffer); i++)
{
cout << " stack1: " << stack1.sstackPush(buffer[i]);
cout << " stack2: " << stack2.sstackPush(buffer[i]);
cout << " stackD: " << stackDefault.sstackPush(buffer[i]);
cout << " i : "<< i << endl;
}
cout << "out of Pushes" << endl;
int i = 0;
memset(buffer, 0x00, 80);
while (!stack1.isempty())
stack1.sstackPop(buffer[i++]);
cout << buffer << endl;
getchar();
}
sstackBuffer[++sstackIndex] = c;
Will write past the end of sstackBuffer when the stack only has one element left.
If you consider a stack of size 1. In the first call to push that line would evaluate to:
sstackBuffer[1] = c;
Which is beyond the memory you've allocated.
Be sure you're aware of the difference between pre-increment and post-increment operators. By your code example I would suggest you use post-increment in push and pre-increment in pop.

A memory error with recursion

This is my code. The program gets some point coordinates and it should enumerate all paths (It should be more complicated in future but this is the essence)
#include <iostream>
#include <utility>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cmath>
using namespace std;
struct Point {
Point () {};
Point (const int &x_, const int &y_) : x{x_}, y{y_} {};
int x, y;
};
double distance(const Point &a, const Point &b) {
return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2));
}
struct Path {
vector<Point> points;
double length;
Path(vector<Point> &p) : points{p}, length{0.0} {};
void add_point(Point &p) {
length += distance(p, points.back());
points.push_back(p);
}
};
vector<Path*> enumerate_paths(vector<Point> &coordinates) {
// assuming coordinates is not empty
vector<Path*> result;
unsigned int size = coordinates.size();
if (size == 1) {
result = {new Path{coordinates}};
return result;
}
vector<Point> coordinates_copy;
vector<Path*> recursion_result;
for(unsigned int i = 0; i < size; ++i) {
cout << "cycle start" << endl << flush;
coordinates_copy = coordinates;
coordinates_copy.erase(coordinates.begin()+i);
// Get results for one coordinate skipped
recursion_result = enumerate_paths(coordinates_copy);
cout << "recursion done" << endl << flush;
// Add the coordinate to each of those results
for_each(recursion_result.begin(), recursion_result.end(),
[&](Path *path) {
path->add_point(coordinates.at(i));});
// Concatenate with previous results
copy(recursion_result.begin(), recursion_result.end(), back_inserter(result));
cout << "cycle end" << endl << flush;
}
cout << "escape recursion" << endl << flush;
return result;
}
int main() {
vector<Point> coordinates = { Point(0,0), Point(1,0), Point(0,1), Point(1,1)};
auto paths = enumerate_paths(coordinates);
cout << "done!" << flush;
}
I believe that the idea of the algorithm is correct, but I'm getting a memory error that I don't understand - double free or corruption (out). I compile with g++ -Wall -std=c++11 without error. What is going on here? Can somebody help?
I can't promise you this is the only problem, but right here:
coordinates_copy.erase(coordinates.begin()+i);
You are eraseing using an iterator from a different vector. Change coordinates.begin() to coordinates_copy.begin().
Also, delete the memory you new ;). Or better yet, switch to smart pointers. Or even forget about pointers entirely and lean on vector's move constructor and the return value optimization instead.

No output when merge function is called

I have a doubt in the following code. Can somebody please explain.
using namespace std;
#define INT_SIZE 32
#define R 4
#define C 4
#define N 4
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#include<limits.h>
#include<stack>
#include<vector>
#include<algorithm>
struct interval{
int start;
int end;
};
bool compareInterval(interval i1, interval i2)
{
return (i1.start < i2.start)? true: false;
}
int merge(vector<interval>& a, int n)
{
stack<interval> s;
sort(a.begin(), a.end(), compareInterval);
s.push(a[0]);
int i=1;
interval temp;
while(i<n)
{
temp = s.top();
s.pop();
if(temp.end > a[i].start && a[i].end > temp.end)
{
temp.end = a[i].end;
s.push(temp);
}
else if(temp.end < a[i].start)
{
s.push(temp);
s.push(a[i]);
}
i++;
}
while(s.size())
{
temp = s.top();
cout << temp.start << " ";
cout << temp.end << "\n";
s.pop();
}
return 0;
}
int main()
{
interval intvls[] = { {6,8}, {1,9}, {2,4}, {4,7} };
vector<interval> intervals(intvls, intvls+4);
for(int i=0;i<4;i++)
{cout << intervals[i].start;
} // This output is not coming when merge function is called
cout << merge(intervals, 4);
}
My doubt is "When I comment the merge function call i.e
// cout << merge(intervals, 4);
When I comment this line, then I am able to see output of cout<<intervals[i].start.
Otherwise, I am not able to see the output.
"
You are not ending your output with a newline. Try:
{cout << intervals[i].start << "\n";}
Without the newline, this output is probably getting hidden amongst all the output produced by merge().
There are few issues with this code.
s.push(a[0]); <-- Only on element is in you stack.
//s.push(a[1]).. you will have to add all other elements like this.
while(i<n)
{
temp = s.top(); <-- for second i s will be empty. Here you must check if stack is empty before getting top element.
s.pop();
}
Your first output is not printed correctly. use std::endl
cout << intervals[i].start << endl;
There is a bug in merge that leads to a segmentation fault. Due to this std::cout is not flushed. If you comment out the line with the merge call, std::cout is flushed when the program exits.