Thứ Năm, 24 tháng 12, 2009

// // Leave a Comment

Lập trình C++ | Một số kĩ thuật cơ bản.

* Câu hỏi : làm sao để set và reset trạng thái của kiểu ouput thông qua hàm flags ?
#include

int main(){
int integer_value = 1000;
double double_value = 0.334343;

//display flags value in original format
std::cout << "-- Original format --\n";
std::cout << "The value of flags variable is : "
<< std::cout.flags() << "\n";
std::cout << "integer value " << integer_value
<<
"\n";
std::cout << "double value " << double_value
<<
"\n";

//use cout flags function to save original format
std::ios_base::fmtflags original_format = std::cout.flags();
//change format
std::cout << std::showbase << std::oct << std::scientific
<< "\n";

std::cout << "-- New format --\n";
std::cout << "The value of flags variable is : "
<< std::cout.flags() << "\n";
std::cout << "integer value " << integer_value
<<
"\n";
std::cout << "double value " << double_value
<< "\n";

//now, restore format
std::cout.flags(original_format);
std::cout << "-- Restore --\n";
std::cout << "The value of flags variable is : "
<<
std::cout.flags() << "\n";
std::cout << "integer value " << integer_value
<<
"\n";
std::cout << "double value " << double_value
<< "\n";

return 0;
}

Output:
-- Original format --
The value of flags variable is : 4098
integer value 1000
double value 0.334343

-- New format --
The value of flags variable is : 011500
integer value 01750
double value 3.343430e-01
-- Restore --
The value of flags variable is : 4098
integer value 1000
double value 0.334343

* Câu hỏi : làm sao in ra kết quả của việc cấp phát lỗi ?
#include

int main(){
double* alloc_arry[5];
for(int x = 0; x < 5; ++x){
alloc_arry[x] = new double[5000000];
if(alloc_arry[x] == 0){
std::cout << "Fail allocating memory...\n" << x << "\n";
break;
}
else{
std::cout << "Successfully allocating new memory for alloc_arry"
<< "at " << x << "\n";
}
delete[] alloc_arry[x];
}

return 0;
}

Output:
Successfully allocating new memory for alloc_arryat 0
Successfully allocating new memory for alloc_arryat 1
Successfully allocating new memory for alloc_arryat 2
Successfully allocating new memory for alloc_arryat 3
Successfully allocating new memory for alloc_arryat 4

* Câu hỏi : làm sao catch fail allocate memory ?
#include
#include

int main(){
double* alloc_arry[5];
try{
for(int x = 0; x < 5; ++x){
alloc_arry[x] = new double[99999999];
std::cout << "Allocating memory...\n" << x << "\n";
}
}
//handle exception
catch(std::bad_alloc &memory_allocation_exception){
std::cout << "Exception occurs !!"
<< memory_allocation_exception.what() << "\n";
}

return 0;
}

Output:
Allocating memory...
0
Allocating memory...
1
Allocating memory...
2
Exception occurs !!std::bad_alloc

* Câu hỏi : làm sao để set new handler cho fail allocating memory.
#include
#include

void custom_new_handler(){
std::cerr << "handle, abort...!";
abort();
}

int main(){
double* alloc_arry[5];
std::set_new_handler(custom_new_handler);
for(int x = 0; x < 5; ++x){
alloc_arry[x] = new double[99999999];
std::cout << "Allocating memory...\n" << x << "\n";
}

return 0;
}

Output:
Allocating memory...
0
Allocating memory...
1
Allocating memory...
2
handle, abort...!

* Câu hỏi : làm sao dùng auto_ptr để allocate memory ?
#include
#include

class Integer{
public :
Integer(int x = 0):value(x){
std::cout << "construct an integer(..) " << value << "\n";
}
~Integer(){
std::cout << "Destructor an integer..." << value << "\n";
}
void set(int x){
value = x;
}
int get() const{
return value;
}
private :
int value;
};

int main(){
std::auto_ptr<Integer> super_pointer(new Integer(99));
super_pointer->set(777);
std::cout << "Integer now : " << (*super_pointer).get() << '\n';
return 0;
}

Output:
construct an integer(..) 99
Integer now : 777
Destructor an integer...777

* Câu hỏi : làm sao convert to C-style string ?
#include
#include

int main(){
std::string first("STRINGS");
const char* fir_ptr = 0;
int m_length = first.length();
char* sec_ptr = new char[m_length + 1];

first.copy(sec_ptr, m_length, 0);
sec_ptr[m_length] = '\0';

std::cout << "string first is = " << first
<< "\n -> convert to C-style " << first.c_str();
std::cout << "\n";
fir_ptr = first.data();

for(int x = 0; x < m_length; ++x){
std::cout << *(fir_ptr + x);
}
std::cout << "second pointer = " << sec_ptr << "\n";
delete[] sec_ptr;

return 0;
}

Output:
string first is = STRINGS
-> convert to C-style STRINGS
STRINGSsecond pointer = STRINGS

* Câu hỏi, làm sao dùng các algorithm đơn giản của STL : binary_seach, find, find_if ?
#include
#include
#include

template <typename C>
inline void print_container(C& container, const char* con_name = "")
{

typename C::const_iterator iter;
std::cout << con_name << "\n";
for(iter = container.begin(); iter != container.end(); ++iter)
{
std::cout << *iter << " - ";
}
std::cout << "\n";
}

bool greater_than_10(int value){
return value > 10;
}

int main(){
const int SIZE = 10;
int arr[SIZE] = {10,2,17,5,16,8,13,11,20,7};

std::vector<int> vect(arr, arr + SIZE);
std::cout << "vector vect contains : ";
print_container(vect, "vector");

std::vector<int>::iterator location;
location = std::find(vect.begin(), vect.end(), 16);

if(location != vect.end())
std::cout << "\n Found 16 at location " << (location - vect.begin()) << "\n";
else
std::cout << "\n 16 not found.\n";


location = std::find(vect.begin(), vect.end(), 100);
if(location != vect.end())
std::cout << "\nFound 100 at location " << (location - vect.begin())
<< "\n";
else
std::cout << "\n 100 not found ";

location = std::find_if(vect.begin(), vect.end(), greater_than_10);
if(location != vect.end()){
std::cout << "\nThe first value greater than 10 is : ";
std::cout << *location << " found at location " << (location - vect.begin());
}
else{
std::cout << "No values greater than 10 were found.";
}

std::sort(vect.begin(), vect.end());
std::cout << "\nAfter sort :\n";
print_container(vect, "vector");

if(std::binary_search(vect.begin(), vect.end(), 13))
std::cout << "\n 13 was found in vect.\n";
else
std::cout << "\n 13 was not found in vect.\n";

if(std::binary_search(vect.begin(), vect.end(), 100))
std::cout << "\n 100 was found in vect.\n";
else
std::cout << "\n 100 was not found in vect.\n";

return 0;
}

Output:
vector vect contains : vector
10 - 2 - 17 - 5 - 16 - 8 - 13 - 11 - 20 - 7 -

Found 16 at location 4

100 not found
The first value greater than 10 is : 17 found at location 2After sort :
vector
2 - 5 - 7 - 8 - 10 - 11 - 13 - 16 - 17 - 20 -

13 was found in vect.

100 was not found in vect.

* Câu hỏi : Làm sao dùng function object in ra các phần tử trong 1 container của STL ?
#include
#include
#include

class print_single_element{
public :
void operator()(int elem) const{
std::cout << elem << " ";
}
};

int main(){
std::vector<int> vect;
for(int x = 0; x < 10; ++x){
vect.push_back(x);
}

for_each(vect.begin(), vect.end(), print_single_element());

return 0;
}

Output:
0 1 2 3 4 5 6 7 8 9

*Câu hỏi : Làm sao dùng function object để tìm trong 1 dãy xem coi số nào là số nguyên tố ?
#include
#include
#include
#include
#include

bool is_prime(int num){
if(num <= 1) return false;
if (num == 2 || num == 3) return true;
if (num % 2 == 0 || num % 3 == 0) return 0;

int variable = 5,
factor = 2,
_limitFactor = static_cast<int>(sqrt(static_cast<double>(num)));
while(variable <= _limitFactor){
if(num % variable == 0)
return false;
variable += factor;
factor = 6 - factor;
}
return true;
}

int main(){
std::list<int> numbers;

for(int x = 13; x < 49; ++x){
numbers.push_back(x);
}

std::list<int>::iterator position;
position = find_if(numbers.begin(), numbers.end(), is_prime);
if(position != numbers.end()){
std::cout << *position << " is prine number.!!\n";
}
else{
std::cout << "No prime number found.\n";
}

return 0;
}

Output:
13 is prine number.!!

* Câu hỏi : Làm sao shift 1 chuỗi lên n units, ví dụ abc->bcd ?
#include
#include

int main() {
std::string text;
std::cout << "Please enter a string : \n";
std::cin >> text;

int units;
std::cout << "\nHow many units would you like to shift: ";
std::cin >> units;

for(std::size_t x = 0; x < text.size(); ++x){
char c = text[x] + units;
std::cout << c;
}
std::cout << "\n";
return 0;
}

Output:
Please enter a string :
abcdef

How many units would you like to shift: 2
cdefgh

*Câu hỏi : làm sao cắt chuỗi bằng 1 chuỗi cho trước ?
#include
#include
#include
#include

std::vector<std::string> tokenize_string_by_delims(std::string line, std::string delims)
{
std::vector<std::string> word;
char *str = new char[line.size()];
std::memcpy(str, line.c_str(), line.size());

for(char *token = std::strtok(str, delims.c_str()); token != 0;
token = std::strtok(0, delims.c_str())){
word.push_back(token);
}

delete[] str;
return word;
}

int main(){
std::string sentence = " first second third fourth ";
std::string delims(" ");
std::vector<std::string> tokens = tokenize_string_by_delims(sentence, delims);

for(unsigned i = 0; i < tokens.size(); ++i)
std::cout << tokens[i] << "\n";

return 0;
}

Output:
first
second
third
fourth

* Câu hỏi : làm sao dùng va_list, va_start, va_end, va_arg trong C bên C++ ?
#include
#include
#include

double average(int count, ...){
double total = 0;
va_list list;
va_start(list, count);

for(int x = 1; x <= count; ++x){
total += va_arg(list, double);
}
va_end(list);

return total/count;
}

int main(){
double first = 35.7;
double second = 123.55;
double third = 13.33;
double fourth = 10.2;

std::cout << "\nAverage of first and second :";
std::cout << average(2, first, second);
std::cout << "\nAverage of first, second and third : \n";
std::cout << average(3, first, second, third);
std::cout << "\nAverage of first, second, third and fourth: \n";
std::cout << average(4, first, second, third, fourth);

return 0;
}

Output:
Average of first and second :79.625
Average of first, second and third :
57.5267
Average of first, second, third and fourth:

* Câu hỏi : làm sao dùng atexit và exit để kết thúc chương trình ?
#include
#include

void print_message(){
std::cout << "Terminating by atexit...\n";
}

int main(){
atexit(print_message);

std::cout << "\t 1 to terminate with atexit.\n";
std::cout << "\t 2 to terminate normally.\n";

int user_choice;
std::cin >> user_choice;

if(user_choice == 1){
exit(EXIT_SUCCESS);
}

std::cout << "Normal termination...";

return 0;
}

Output:
         1 to terminate with atexit.
2 to terminate normally.
1
Terminating by atexit...

0 comments: