c++11 - C++ program ( print out n words in alphabetical order ) runtime error -



c++11 - C++ program ( print out n words in alphabetical order ) runtime error -

i started larn c++ programing, , watched many of posts , answers involvement when mind lack creativity. have few issues code right here. should show "n" words in alphabetical order. "n" beingness introduce user , words well. weird error, give me few hints on should do?

#include <iostream> #include <vector> #include <string> int main () { int n=0; std::string cuvant; std::vector<std::string> lista_cuvinte; std::cout<<" cate cuvinte doriti sa comparati = "<< std::endl; std::cin>> n; (int i=0; i<n; i++) { std::cout<<"cubantul al " << + 1 <<" -lea = "; std::cin>> cuvant; lista_cuvinte.push_back(cuvant); (int i=0; < n; i++) { (int j=i + 1; j < n; j++) { if (lista_cuvinte.at(i) > lista_cuvinte.at(j)) { std::string temp=lista_cuvinte.at(i); lista_cuvinte[i]=lista_cuvinte.at(j); lista_cuvinte[j]=temp; i=i-1; break; std::cout<< temp << std::endl; } } } } homecoming 0; }

you doing lot things wrong. sorting starts before info read in in code. code after break never executed. , there no output.

but can accomplish same result much simpler using sort algorithm. believe code learning, maybe makes sense hand. not :-)

#include <iostream> #include <vector> #include <string> int main () { int n=0; std::string cuvant; std::vector<std::string> lista_cuvinte; std::cout<<" cate cuvinte doriti sa comparati = "<< std::endl; std::cin>> n; // read info (int i=0; i<n; i++) { std::cout<<"cubantul al " << + 1 <<" -lea = "; std::cin>> cuvant; lista_cuvinte.push_back(cuvant); } // sort info (int i=0; < n; i++) { (int j=i + 1; j < n; j++) { if (lista_cuvinte.at(i) > lista_cuvinte.at(j)) { std::string temp=lista_cuvinte.at(i); lista_cuvinte[i]=lista_cuvinte.at(j); lista_cuvinte[j]=temp; i=i-1; break; } } } // output info (int i=0; i<n; i++) { std::cout << lista_cuvinte[i] << std::endl; } homecoming 0; }

and std::sort code in section sorting reduces to:

// sort info std::sort( lista_cuvinte.begin(), lista_cuvinte.end());

thats all!

as hint writing , finding errors in general: please utilize debugger. code throws exception. debugger grab , go in backtrace point error occurs. in code access out of range array, because info not read in @ point of execution.

c++ c++11

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -