C++ std::sort function gets not finished? - c++

im currently setting up the highscore-part for a game and I have a very weird problem because of the weird behaviour of the std::sort function.
Im doing the whole thing in RAD Studio 10.2 (Embarcadero IDE) in C++.
So he is my code:
std::string Line;
int count = 0;
int i = 0;
ifstream File("Highscore.txt");
if(File.is_open())
{
while(getline(File, Line))
{
count += 1;
}
File.close();
}
ifstream ReadFile("Highscore.txt");
if(ReadFile.is_open())
{
string *scores = NULL;
scores = new string[count];
while(getline(ReadFile, Line))
{
scores[i] = Line;
i += 1;
}
ReadFile.close();
std::sort(scores, (scores+count));
UnicodeString Uscores1 = scores[0].c_str();
UnicodeString Uscores2 = scores[1].c_str();
UnicodeString Uscores3 = scores[2].c_str();
UnicodeString Uscores4 = scores[3].c_str();
UnicodeString Uscores5 = scores[4].c_str();
LScore1->Caption = Uscores1;
LScore2->Caption = Uscores2;
LScore3->Caption = Uscores3;
LScore4->Caption = Uscores4;
LScore5->Caption = Uscores5;
}
I get no errors from the compiler/linker and everything work should fine.
The string array gets filled correctly and so on.
But its not sorting.
To show the problem to you I made a screenshot - on the left you can see the txtfile with the scores; on the right you can see the output after the sorting algorithm:
My question now is why this is happening?
Thanks for you help

Welcome to C++. Since you want to list numbers by rank, read them as int not string. Forget about operator new. You will not need it for years, if ever. Use standard containers like std::vector, which take care of the memory allocation and de-allocation transparently.
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
int main() {
using namespace std;
vector<int> scores;
{
ifstream inp("Highscore.txt");
int next;
while (inp >> next) {
scores.push_back(next);
}
}
sort(scores.begin(), scores.end());
for (auto s : scores) {
cout << s << '\n';
}
return 0;
}

How about something like:
int i = 0;
int * scoresInteger = NULL;
scoresInteger = new int[count];
for(i = 0; i < count; i++)
{
scoresInteger[i] = std::stoi(scores[i]);
}
std::sort(scoresInteger, scoresInteger + count);
If you need to, you can convert the integers back into strings using targetStrings[i] = std::to_string(scoresInteger[i]).
string * targetScores = NULL;
targetScores = new std::string[count];
for(i = 0; i < count; i++)
{
targetScores[i] = std::to_string(scoresInteger[i]);
}
delete [] scoresInteger;
scoresInteger = NULL;
Don't forget to delete [] targetScores later.

My question now is why this is happening?
Because your scores are compared as strings and not as ints. Because of that "3" is greater that "25"
std::cout << std::boolalpha << (std::string("3") > std::string("25")) << std::endl; // true
Luckily you can pass a custom comparator (or lambda) to the std::sort to make it behave just as you want:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
const int count = 5;
std::string scores[count] = { "35","25","3","4","5" };
// TWEAKED SORT
std::sort(scores, scores + count, [](std::string const &s1, std::string const &s2)
{
return std::stoi(s2) < std::stoi(s1);
});
// TEST
for (auto const &s : scores)
{
std::cout << s << std::endl;
}
}
The compared strings in the above example are converted to ints and then compared, resulting in the desired sorting order.
35
25
5
4
3
Please note that I do not agree with the rest of your code and I think you should rethink the implementation, as it would be much easier, safer and more efficient to use std::vector<std::string> for your task.

Related

How to find the index of element (and a few other things)

I was writing a code that would substitute some random 17 character strings into a single alphabet, and I can't find a way. Basically, what I'm trying to do is this:
char strings[] = {
"L-nIbhm5<z:92~+,x",
"9bC5f0q#qA(RKZ>|r",
"9bC5f0q#qA(RKZ>|r",
"k=5,ln(08IAl(gGAK",
"|N,8]dGu)'^MaYpu[",
"!&,Y*nz8C*,J}{+d]",
"Us9%^%?n5!~e##*+#",
"zF8,1KV#¥]$k?|9R#",
"0B4>=nioEjp>4rhgi",
}
char alphabet[]{
"a","b","c","d","e","f","g","h","i",
}
replace(std::string str){
/**get str and then see the index of the corresponding string in strings[], and replace the string with alphabet[index number], while deleting the original string part that was replaced**/
int main(){
cin >> std::string replace;
replace(replace);
example input: L-nIbhm5<z:92~+,x9bC5f0q#qA(RKZ>|r9bC5f0q#qA(RKZ>|r
expected output: abc
EDIT:
New Code
Changes from the original code
It also has a bigger array than the simplified version(previous code). It displays the structure of the full program.(where the strings are routed to and why)
Basically What it's doing
getting input from user, put it in the input variable, input goes through algorithm() function untouched, and then goes to the replace function and is replaced. It then the replaced string gets returned back through the original route to the main function, where it is displayed.
I've kept the arrays a string type because the const char* gave me a segmentation error.
std::string Subs[53]=
{
"LQlMv]G5^^1kcm?fk",
"7W^S;/vB(6%I|w[fl",
"<w7>4f//Z55ZxK'z.",
"_W5g(lu<pTu3^_A7n",
"OfLm%8:EF}0V1?BSS",
"|+E6t,AZ~XewXP17T",
"L-nIbhm5<z:92~+,x",
"L-nIbhm5<z:92~+,x",
"9bC5f0q#qA(RKZ>|r",
"9bC5f0q#qA(RKZ>|r",
"k=5,ln(08IAl(gGAK",
"|N,8]dGu)'^MaYpu[",
"!&,Y*nz8C*,J}{+d]",
"Us9%^%?n5!~e##*+#",
"zF8,1KV#¥]$k?|9R#",
"0B4>=nioEjp>4rhgi",
"EG#0[W9.N4i~E<f3x",
"(0Pwkk&IPchJHs.7A",
"7XgmQ6fW<|J+NY[m0",
".g4CwX/DU!!~!zbtZ",
"+_U'qn_/9Fo|gT/!n",
"=0s(mYh&F%y=MBS5(",
"cg71(}bo+Q5P8F[T6",
"lc|a\%5.9pOpooU+QR",
"E_(3A:o+.]qL3MYA6",
"H#O'X_RiVS#8l0bKD",
"Y1gbGD`~8d>HSWN35",
"LQlMv]G5^^1kcm?fk",
"T4}gI;`BFVfhw=-sf",
"6BHMA0IRix]/=(jht",
"yS$=#Jdpp?P2k6SMQ",
"t1~|kkh+>4d>}OQ`a",
"2Y-\\CU\"944yBluWD5",
"'M\\ZbIX5{`Xd;qi!o",
"?N+RtVqj_r(C5##0\"",
"2;*Livh?V$X/8z#Md",
")IN|7FOs2l-mAM[d#",
"(~f268J},xXrK'Rp'",
"&r/qf9fFHnzV!RzH/",
"}naDRH4p$NI2a).t,",
"{8DM+7!.Mge|~fnO|",
")r[#nI0YDH>6cE38p",
"(0Pwkk&IPchJHs.7A",
")r[#nI0YDH>6cE38p",
"8M-=cQFQ,pPo7eu=p",
"0PHw=/|(tZ1}FHm/'",
"[su`'0Oybc.\"-/W5)",
"1uHl[IC7Sr#NUJV;I",
"8z8%,jK0CDOkJz8I?",
"3Ao2yXDN%YzpE&Suy",
"zNs`7E'e/$i8VqaUL",
"bzHmA^K2>7`UZ?!AO",
};
std::string Alphabet[53] =
{
" ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","r","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
};
std::string replace(std::string rep) {
int len = sizeof(Subs)/sizeof(Subs[0]);
std::stringstream ss1;
for(int i = 0; i < len; i++) {
if (rep.find(Subs[i]) != std::string::npos) {
ss1 << Subs[i];
}
}
std::string input = ss1.str();
return input;
}
std::string algorithm(std::string input)
{
//some other algorithms come here(not relative to this question)
input = replace(input);
return input;
}
int main(void){
int ed;
std::cin >> ed;
if(ed == 1){
//different function(not relative to the question)
}
else if(ed == 0){
std::string input;
std::cin >> input;
input = algorithm(input);
std::cout << input << std::endl;
}
else{
std::cout << "1 or 0" << std::endl;
main();
}
return 0;
}
example input: L-nIbhm5<z:92~+,x9bC5f0q#qA(RKZ>|r9bC5f0q#qA(RKZ>|r
expected output: abc
actual output: L-nIbhm5<z:92~+,xL-nIbhm5<z:92~+,x9bC5f0q#qA(RKZ>|r9bC5f0q#qA(RKZ>|r
Sorry it's become long.
There are few mistakes in above code :
char array initialization is not correct.
method body for main and replace method is not closed.
Currently by default return type of replace method is int.
There is string#find method which can be helpful here.
I have tried to make those fixes and here is updated code in C++17 :
#include <iostream>
#include <sstream>
using namespace std;
const char *strings[9] = {
"L-nIbhm5<z:92~+,x",
"9bC5f0q#qA(RKZ>|r",
"9bC5f0q#qA(RKZ>|r",
"k=5,ln(08IAl(gGAK",
"|N,8]dGu)'^MaYpu[",
"!&,Y*nz8C*,J}{+d]",
"Us9%^%?n5!~e##*+#",
"zF8,1KV#¥]$k?|9R#",
"0B4>=nioEjp>4rhgi"
};
const char *alphabet[9] = {
"a","b","c","d","e","f","g","h","i"
};
void replace(std::string rep) {
int len = sizeof(strings)/sizeof(strings[0]);
std::stringstream ss1;
for(int i = 0; i < len; i++) {
if (rep.find(strings[i]) != std::string::npos) {
ss1 << alphabet[i];
}
}
std::cout << ss1.str();
}
int main(){
std::string rep;
cin >> rep;
replace(rep);
}
For reference : https://onlinegdb.com/Bd9DXSPAa
Note - Above code is just for reference, please make sure to add all test cases handling.
I made a c++17 version for your code.
Replacing 'c' style arrays and pointers with C++ style containers, iterators.
And using std::string::replace function. Use the standardlibrary if you can,
its tested and well documented.
#include <algorithm>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
// std::vector/std::array instead of 'c' style arrays.
// allows us to us range based for loops later.
std::vector<std::string> strings =
{
"L-nIbhm5<z:92~+,x",
"9bC5f0q#qA(RKZ>|r",
"k=5,ln(08IAl(gGAK",
"|N,8]dGu)'^MaYpu[",
"!&,Y*nz8C*,J}{+d]",
"Us9%^%?n5!~e##*+#",
//"zF8,1KV#¥]$k?|9R#", // <<== I commented out this line, ¥ is not a valid charcter in my environment
"0B4>=nioEjp>4rhgi"
};
// a string is already an array of characters.
std::string alphabet{ "abcdefghijkl" };
std::string replace_with_alphabet(const std::string& input)
{
std::string retval{ input };
std::size_t index{ 0 };
// range based for, it will keep the order of the vector.
for (const auto& str : strings)
{
// look if you can find any of the predefined strings
// in the input strings.
const size_t pos = retval.find(str, 0);
// if found
if (pos != std::string::npos)
{
// get the next character from the alphabet
std::string replacement{ alphabet[index++] };
// use std::string::replace for replacing the substring
const size_t len = str.length();
retval.replace(pos, len, replacement, 0);
}
}
return retval;
};
/**get str and then see the index of the corresponding string in strings[], and replace the string with alphabet[index number], while deleting the original string part that was replaced**/
int main()
{
auto output = replace_with_alphabet("L-nIbhm5<z:92~+,x9bC5f0q#qA(RKZ>|rk=5,ln(08IAl(gGAK");
std::cout << output << std::endl;
}

Array print function

I am trying to create a function that prints the elements of an array. I set it up so it calculates the size of the array, but I cannot figure why it doesn't work. Can you give me some suggestions?
Thanks!
#include <iostream>
#include <string>
using namespace std;
void print_array(string s){
for(int i = 0; i < ( sizeof(s) / sizeof(s[0]) ); i++){
cout << s[i] << "\n";
}
}
int main()
{
string names[5] = {"Dante", "Greg", "Bob", "Victor", "Saber"};
print_array(names);
}
Welcome to Stack Overflow! Be aware that there are many questions similar to this that have received answers.
As mentioned in a comment, you would need to specify the size of the array if you plan on passing it into a function, because the compiler will look at it not as an array of strings (string s[]), but as a pointer to strings (string s*). Thus, you would need to modify it a little like so:
#include <iostream>
#include <string>
using namespace std;
void print_array(string s[], int size){
for(int i = 0; i < size; i++)
{
cout << s[i] << "\n";
}
}
int main()
{
string names[5] = {"Dante", "Greg", "Bob", "Victor", "Saber"};
print_array(names, sizeof(names) / sizeof(names[0]));
}
You are passing a string instead of an array of strings. You could modify your code by using vectors like this:
void print_array(const std::vector<std::string> &vector){
for (const auto &string : vector) {
std::cout << string << "\n";
}
}
int main()
{
std::vector<std::string> names = {"Dante", "Greg", "Bob", "Victor", "Saber"};
print_array(names);
}
Using vectors allows you to use auto generated for loops, wich are easy to read and use.

Reversing a string? a more optimal way

#include<iostream>
#include<string.h>
using namespace std;
int main ()
{
char str[50], temp;
int i, j;
cout << "Enter a string : ";
gets(str);
j = strlen(str) - 1;
for (i = 0; i < j; i++,j--)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
cout << "\nReverse string : " << str;
return 0;
}
Is there any more optimal way without using this function to reverse a string ? The function will start from the last position of S and will continue to be copied the string reversed. Instead of using the tmp variable.
string reverse(string s)
{
string reversed ;
for(int is.length();int i >0;--)
{
reversed +=s[i];
}
return reversed;
}
You can use std::reverse to reverse the string in place, with complexity being (last - first)/2 swaps, which is exactly the complexity of the first function, but is cleaner.
The second method has an overhead of extra allocation which will probably end up being slower.
I have tested the two option with quite large files.
The std::reverse(ss.begin(), ss.end()); corresponds to the first option (no copy)
The ss_r = new std::string(ss.rbegin(), ss.rend()); corresponds to the second option (copy)
#include <iostream>
#include <fstream>
#include <chrono>
#include <string>
#include <algorithm>
//Just for reading the file
std::string read_file(char * file_name)
{
std::ifstream file(file_name);
std::string ss;
file.seekg(0, std::ios::end);
std::cout << file.tellg() <<std::endl;
ss.resize(file.tellg());
file.seekg(0, std::ios::beg);
file.read(&ss[0], ss.size());
file.close();
return ss;
}
//The real test
int main(int arg, char ** args)
{
std::string ss = read_file(args[1]);
std::string * ss_r=NULL;
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
start = std::chrono::high_resolution_clock::now();
if(args[2]==std::string("copy"))
{
//Second option
ss_r = new std::string(ss.rbegin(), ss.rend());
}
else
{
//First option
std::reverse(ss.begin(), ss.end());
}
end = std::chrono::high_resolution_clock::now();
int elapsed_nano_seconds = std::chrono::duration_cast<std::chrono::nanoseconds>
(end-start).count();
if(ss_r!=NULL)
{
std::cout<<*ss_r<<std::endl;
}
else
{
std::cout<<ss<<std::endl;
}
std::cout << elapsed_nano_seconds<<std::endl;
}
Testing with icpc test.cpp -O3 --std=c++11
a.out Test_file no_copy runs in 160 microseconds
a.out Test_file copy runs in 320 microseconds
On the other hand with the first option you lost the original string...
So in summary if you don't care about loosing the original string go with std::reverse if you want to keep it go with std::string(ss.rbegin(), ss.rend());

Gettin Lvalue Error in C++ array

I need to sort the first name and then last name of of student and then display the fully sorted names on screen using structure in C++. I tried but compiler showing Lvalue Required error - in these line
tfname = s[i].fname;
s[i].fname = s[j].fname;
s[j].fname = tfname;
tlname = s[i].lname;
s[i].lname = s[j].lname;
s[j].lname = tlname;
Here the complete code
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <string.h>
struct student
{
char fname[20];
char lname[20];
int id_no;
};
typedef student S;
void main()
{
S s[25];
char tfname[20], tlname[20];
int t;
for(int i = 0; i<25; i++)
{
cout<<"\n Enter Student's first name:";
cin>>s[i].fname;
cout<<"\n Enter Student's last name:";
cin>>s[i].lname;
cout<<"\n Enter ID NO";
cin>>s[i].id_no;
}
for(i = 0; i<24; i++)
{
for(int j = i+1; j<25; j++)
{
if(strcmp(s[i].fname, s[j].fname)>0)
{
tfname = s[i].fname;
s[i].fname = s[j].fname;
s[j].fname = tfname;
tlname = s[i].lname;
s[i].lname = s[j].lname;
s[j].lname = tlname;
t = s[i].id_no;
s[i].id_no = s[j].id_no;
s[j].id_no = t;
}
else
{
if(strcmp(s[i].fname, s[j].fname)==0)
{
if(strcmp(s[i].lname, s[j].lname)>0)
{
tfname = s[i].fname;
s[i].fname = s[j].fname;
s[j].fname = tfname;
tlname = s[i].lname;
s[i].lname = s[j].lname;
s[j].lname = tlname;
t = s[i].id_no;
s[i].id_no = s[j].id_no;
s[j].id_no = t;
}
}
}
}
cout<<"\n\n FIRST NAME \t LASTNAME \t ID NO ";
for(int i = 0; i<25; i++)
{
cout<<"\n"<< c[i].fname<<"\t" <lt; c[i].lname <<="" <
}
getch();
}
}
Kindly help me how can I solve this error
Use std::vector and std::string instead of arrays. Arrays have all kinds of problems in use cases such as yours. One of their big problems if that you cannot pass around or return them like "normal" objects, e.g. of type int or double. Their "second-class citizen" status in the C++ language also causes the strange behaviour you've observed in your program.
int GetInt() // works fine
{
return 123;
}
void DoSomethingWithDouble(double d) // works fine
{
// ...
}
char[] GetArray() // does not even compile
{
// ...
}
void DoSomethingWithArray(int array[]) // does not work as expected, either
{
// ...
}
This is why in C++, we use std::string, std::vector or other sophisticated classes which allow us to treat strings or collections exactly (or almost exactly) like simple (so-called "primitive") types such as int or double:
std::string GetString()
{
// ...
}
void DoSomethingWithString(std::string const &s) // you should use const & here because
// it does not cost you anything and may
// increase speed of your program
{
// ...
}
std::vector<int> GetInts()
{
// ...
}
void DoSomethingWithInts(std::vector<int> const &v) // you should use const & here because
// it does not cost you anything and
// may increase speed of your program
{
// ...
}
You can even assign them completely safely and with no special syntax:
std::vector<int> v1;
std::vector<int> v2;
v1 = v2;
std::string s1;
std::string s2;
s1 = s2;
And you can create string vectors, and they will behave exactly as you expect:
std::vector<std::string> string_vector;
string_vector.push_back("abc");
string_vector[0][0] = 'A';
std::cout << string_vector[0]; // prints "Abc"
Arrays do have their place in C++, but not for beginners and not in high-level programming.
You cannot swap strings this way. Strings should be copied using strcpy().
strcpy(tfname, s[i].fname);
strcpy(s[i].fname, s[j].fname);
strcpy(s[j].fname, tfname);
Another way is #include <string> and declare student::fname, student::lname, tfname and tlname as std::string. Then you could use assignment operator to copy them correctly.
Arrays has no the assignment operator. Instead of it you have to copy elements from one array to another. As in your code arrays has type char and designed to store strings you should use standard C function std::strcpy declared in header <cstring>
So this code snippet
tfname = s[i].fname;
s[i].fname = s[j].fname;
s[j].fname = tfname;
tlname = s[i].lname;
s[i].lname = s[j].lname;
s[j].lname = tlname;
will look the following way
std::strcpy( tfname, s[i].fname );
std::strcpy( s[i].fname,s[j].fname );
std::strcpy( s[j].fname, tfname );
std::strcpy( tlname, s[i].lname );
std::strcpy( s[i].lname, s[j].lname );
std::strcpy( s[j].lname, tlname );
The other approach is to use standard class std::array. In this case you may use the assignment operator. For example
#include <array>
//...
struct student
{
std::array<char, 20> fname;
std::array<char, 20> lname;
int id_no;
};
And at last you could use class std::string instead of raw character arrays.
If your task description contains C++, struct, and sort, what about this version?
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct Student
{
std::string fname;
std::string lname;
int id_no;
};
/// checks order after comparing (fname, then lname)
/// (usable with std::sort)
bool operator<(const Student& lhs, const Student& rhs)
{
int c=lhs.fname.compare(rhs.fname);
if (c < 0) {
return true;
} else if (c > 0) {
return false;
}
return lhs.lname < rhs.lname;
}
/// write student to standard output stream
/// (usable with std::for_each)
void out_student(const Student& s)
{
std::cout << s.fname << " " << s.lname << " " << s.id_no << std::endl;
}
int main()
{
std::list<Student> students;
// entering students left out
std::sort(students.begin(), students.end());
std::for_each(students.begin(), students.end(), out_student);
return 0;
}

Seg Fault when creating dynamic array of strings

My friend is writing a text-based game and asked me to look at this code that was crashing. I debugged it and it was getting a seg fault when creating a dynamic array. I'm not sure exactly why, I recommended he just avoid pointers altogether and use a vector so hopefully that will solve his problem but I'm curious as to what exactly is going wrong here. Here's his code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
class nation
{
public:
void init();
string genName();
string getName();
private:
string myName;
int* myBorderPoints;
};
string nation::getName()
{
return myName;
}
string nation::genName()
{
int listLength = 0, listPos = 0, listRand = 0;
string nameToGen = "";
string* namePartList;
ifstream fileName;
fileName.open("NamePart1.txt");
listLength = fileName.tellg();
namePartList = new string[listLength]; // Seg fault here
while (fileName.good())
{
while (!fileName.eof())
{
getline(fileName,namePartList[listPos]);
listPos += 1;
}
}
listRand = rand() % listLength;
nameToGen += namePartList[listRand];
fileName.close();
listLength = 0;
listPos = 0;
listRand = 0;
nameToGen = "";
fileName.open("NamePart2.txt");
listLength = fileName.tellg();
namePartList = new string[listLength];
while (fileName.good())
{
while (!fileName.eof())
{
getline(fileName,namePartList[listPos]);
listPos += 1;
}
}
listRand = rand() % listLength;
nameToGen += namePartList[listRand];
fileName.close();
return nameToGen;
}
void nation::init()
{
srand(time(NULL));
myName = genName();
}
int main()
{
nation testNation;
testNation.init();
cout << testNation.getName();
return 0;
}
You are calling tellg:
listLength = fileName.tellg();
without having read anything, which depending on whether the file was opening successfully or not will return 0 or -1 and so you will have this called:
namePartList = new string[listLength]
with a probably a undesirable value. I am pretty sure it is returning -1 since allocating a zero sized should be ok.
This also applies later on the code as well, going with std::vector probably makes more sense.