c++ primer 5 exercise 10.9

c++ primer 5 exercise 10.9

实现自己的elimDups程序。测试你的程序,分别在读取输入后、调用unique后以及调用erase后打印vector
程序实现:

// sort and elimDups
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using std::cin;
using std::cout;
using std::ends;
using std::endl;
using std::string;
using std::vector;
using std::sort;
using std::unique;

vector<string> strToVec(const string line, const string separators);
void show(vector<string> const &words);
void elimDups(vector<string> words);
int main(void)
{
        const string Separators = " \t:;,\n\r\f\v";
        string str("the quick red fox jumps the slow red turtle");

        // string turn on vector<sting>
        vector<string> vec;
        vec = strToVec(str, Separators);

        // show vector<string>
        cout << "string to vector<sting>..." << endl;
        show(vec);

        // elimDups()
        cout << "\nelimDups()..." << endl;
        elimDups(vec);

        return 0;
}

vector<string> strToVec(const string line, const string separators)
{
        vector<string> vec;
        string word;
        std::string::size_type startPos = 0, endPos = 0;
        std::string::size_type wordLen = 0;

        while ((startPos = line.find_first_not_of(separators,
                endPos)) != std::string::npos) {
                endPos = line.find_first_of(separators, startPos);
                if (endPos == std::string::npos)
                        wordLen = line.size() - startPos;
                else
                        wordLen = endPos - startPos;
                word.assign(line.begin() + startPos,
                        line.begin() + startPos + wordLen);
                vec.push_back(word);
        }

        return vec;
}

void show(vector<string> const &words)
{
        for (const auto s : words)
                cout << s << " ";
        cout << endl;

        return;
}

void elimDups(vector<string> words)
{
        sort(words.begin(), words.end());
        show(words);

        auto end_unique = unique(words.begin(), words.end());
        show(words);

        words.erase(end_unique, words.end());
        show(words);

        return;
}

程序测试结果:

[lhf@localhost 10-9]$ ./elimDups
string to vector<sting>...
the quick red fox jumps the slow red turtle

elimDups()...
fox jumps quick red red slow the the turtle
fox jumps quick red slow the turtle the red
fox jumps quick red slow the turtle

字符串排序函数(单词排序,唯一)

本程序演示:怎样将一个string字符串输入到一个vector中,每个元素对应一个单词。

// sort and unique
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using std::cin;
using std::cout;
using std::ends;
using std::endl;
using std::string;
using std::vector;
using std::sort;

void show(vector<string> const &words);
void elimDups(vector<string> &words);
int main(void)
{
        string str("the quick red fox jumps over the slow red turtle");
        //string str("");

        string separators = " \t:;,\v\n\r\f";
        string word;
        vector<string> vec;
        std::string::size_type startPos = 0, endPos = 0;
        std::string::size_type /*count = 0,*/ wordLen = 0;
        while ((startPos = str.find_first_not_of(separators, endPos))
                != std::string::npos) {
//              ++count;
                endPos = str.find_first_of(separators, startPos);
                if (endPos == std::string::npos) {
                        wordLen = str.size() - startPos;
                } else {
                        wordLen = endPos -startPos;
                }
                word.assign(str.begin() + startPos,
                        str.begin() + startPos + wordLen);
                vec.push_back(word);
        }
        // show vec info
        show(vec);

        elimDups(vec);

        return 0;
}

void elimDups(vector<string> &words)
{
        sort(words.begin(), words.end());
        show(words);
        auto end_unique = unique(words.begin(), words.end());
        show(words);
        words.erase(end_unique, words.end());
        show(words);
}

void show(vector<string> const &words)
{
        for (auto s : words)
                cout << s << " ";
        cout << endl;

        return;
}


程序输出:

[lhf@localhost study]$ ./23
the quick red fox jumps over the slow red turtle
fox jumps over quick red red slow the the turtle
fox jumps over quick red slow the turtle the red
fox jumps over quick red slow the turtle

c++primer 9.51习题

设计一个类,它有三个unsigned成员,分别表示年月日。为其编写构造函数,接受一个表示日期的string参数。你的构造函数能够处理不同的数据格式,如January 1, 1900 1/1/1900 Jan 1 1900等

// January 1, 1900      1/1/1900        Jan 1 1900
#include <iostream>
#include <vector>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::ends;
using std::vector;
using std::string;
using std::stoi;

class Date {
public:
        vector<string> full_month{
                "January", "February", "March", "April", "May", "June", "July",
                "August", "September", "October", "November", "December"
        };
        vector<string> abb_month{
                "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept",
                "Sep", "Oct", "Nov", "Dec"
        };
public:
        Date(const string& info);
        ~Date(void) {}
        void print_info(void)
        {
                cout << "_" << month << "." << day << "."<< year << "_\n";
                return;
        }
private:
        void init(void)
        {
                year = 1900;
                month = 1;
                day = 1;

                return;
        }
private:
        unsigned year;
        unsigned month;
        unsigned day;
};

int main(void)
{

        cout << "2343" << endl;
        Date error("2343");
        error.print_info();
        cout << string(20, '*') << endl;

        cout << "October 21, 2002" << endl;
        Date date1("October 21, 2002");
        date1.print_info();
        cout << string(20, '*') << endl;

        cout << "2/8/1995" << endl;
        Date date2("2/8/1995");
        date2.print_info();
        cout << string(20, '*') << endl;

        cout << "May 12 2011" << endl;
        Date date3("May 12 2011");
        date3.print_info();

        return 0;
}

Date::Date(const string& info)
{
        std::string::size_type pos;
        pos = info.find_first_of(", /");

        // error info
        if (pos == std::string::npos) {
                init();
                cout << "error date format: init" << endl;
                return;
        }

        // 1/1/1900
        std::string::size_type pos1 = info.find_first_of('/'),
                pos11 = pos1;
        if (pos1 != std::string::npos) {
                day = stoi(info.substr(0, pos1));
                pos11 = info.find_first_of('/', pos1 + 1);
                month = stoi(info.substr(pos1 + 1, pos11));
                year = stoi(info.substr(pos11 + 1, info.size() - 1));
                return;
        }

        // January 1, 1990 and Jan 1 1900
        std::string::size_type pos2 = info.find_first_of(' '),
                pos3 = pos2, pos33 = pos3, pos22 = info.find_first_of(',');
        if (pos22 != std::string::npos) {
                // January 1, 1990
                string str_month = info.substr(0, pos2);
                vector<string>::size_type n = 0;
                for (; n != full_month.size(); ++n) {
                        if (!full_month[n].compare(str_month))
                                break;
                }
                if (n == full_month.size()) {
                        init();
                        cout << "format(January 1, 1990) error: init" << endl;
                        return;
                } else {
                        month = n + 1;
                }
                day = stoi(info.substr(pos2 + 1, pos22));
                year = stoi(info.substr(pos22 + 1, info.size() -1));

                return;
        } else if (info.find_first_of(' ', pos3 + 1) != std::string::npos) {
                // Jan 1 1990
                vector<string>::size_type n = 0;
                string str_month = info.substr(0, pos3);
                for (; n != abb_month.size(); ++n) {
                        if (!abb_month[n].compare(str_month))
                                break;
                }
                if (n == abb_month.size()) {
                        init();
                        cout << "format(Jan 1 1990) error: init" << endl;
                        return;
                } else if (n < 9) {
                        month = n + 1;
                } else if (n == 9) {
                        month = n;
                } else {
                        month = n - 1;
                }
                pos33 = info.find_first_of(' ', pos3 + 1);
                day = stoi(info.substr(pos3 + 1, pos33));
                year = stoi(info.substr(pos33 + 1, info.size() - 1));
        } else {
                init();
                cout << "other error format: init" << endl;

                return;
        }

        return;
}

测试运行结果:

$ ./my_date
2343
error date format: init
_1.1.1900_
********************
October 21, 2002
_10.21.2002_
********************
2/8/1995
_8.2.1995_
********************
May 12 2011
_5.12.2011_

linux 控制台显示中文乱码

linux 控制台显示乱码

linux 语言编码设置在/etc/sysconfig/i18n文件中。建议设置UTF-8
全局语言编码设置具体如下,这个是针对所有的语言编码设置(包括控制台,窗体标题,GUI内容显示等等)

#vi /etc/sysconfig/i18n

在文件中添加如下代码:

LANG="zh_CN.UTF-8"

下面针对控制台设置如下

#vi ~/bash_profile

将LANG代码更改成如下代码:

LANG=zh_CN.UTF-8
export LANG

简单哈希表(hash table c)

hash表,有时候也被称为散列表。

引自wiki: 散列表(Hash table,也叫哈希表),是根据关键字(Key value)而直接访问在内存存储位置的数据结构。也就是说,它通过计算一个关于键值的函数,将所需查询的数据映射到表中一个位置来访问记录,这加快了查找速度。这个映射函数称做散列函数,存放记录的数组称做散列表。
下面我们可以写一个简单的hash操作代码。

定义哈希表数据类型

/* hash.h */
#include <stdbool.h>

#ifndef HASH_H
#define HASH_H

typedef struct _NODE {
        int data;
        struct _NODE *next;
} NODE;

typedef struct _HASH_TABLE {
        NODE *value[10];
} HASH_TABLE;

HASH_TABLE *create_hash_table(void);
NODE *find_data_in_hash(HASH_TABLE *pHashTab, int data);
void print_hash_table(HASH_TABLE *pHashTab);
bool insert_data_into_hash(HASH_TABLE *pHashTab, int data);
bool delete_data_from_hash(HASH_TABLE *pHashTab, int data);
bool delete_idx_data_from_hash(HASH_TABLE *pHashTab, int idx);
bool delete_all_data_from_hash(HASH_TABLE *pHashTab);
bool reset_hash_table(HASH_TABLE *pHashTab);
bool destroy_hash_table(HASH_TABLE **ppHashTab);

#endif//HASH_H

继续阅读

C数据类型的DWORD

C数据类型的长度

类型  ILP32(位数)     LP64(位数)
char        8            8
short      16            16
int        32            32
long       32            64
long long  64            64
point      32            64

宏定义

    WORD       ->   unsigned   short 
    DWORD      ->   unsigned   int 
    LPVOID     ->   void   * 
    UINT       ->   unsigned   int 

按文件名存储-哈希表

通过散列函数将数据值和它的存储位置联系起来。即通过精心地向表载入元素实现,从而提高访问速度。本例中采取的解决冲突的办法是建立一个链表,挂在这个位置的后面,所有散列函数值为这个位置的元素都添加到这个链表中,可以从头部插入也可以从尾部追加,甚至可以再这个位置后面再挂一个散列表。代码实现了将文件名按字母a-z分类,不区分大小写。先以数组存储各节点,当发生冲突后即将节点加入链表中。然后遍历显示所有的文件名。

/* a2z.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define HASHSIZE 26
#define FILENAMELENGTH 20
#define TRUE 1
#define FALSE 0

struct file {
        char name[FILENAMELENGTH];
        struct file *next;
};

struct file * files[HASHSIZE];

char case_insensitive(char ch)
{
        if (isupper(ch))
                return ch - 'A' + 'a';
        return ch;
}

void init(void)
{
        int i;
        for (i = 0; i < HASHSIZE; i++)
                files[i] = NULL;
}

int hash(char *s)
{
        return case_insensitive(s[0]) - 'a';
}

int search(char *s)
{
        int num = hash(s);
        if (files[num] != NULL) {
                struct file *p = files[num];
                while (p != NULL) {
                        if (strcmp(p->name, s) == 0)
                                return TRUE;
                        p = p->next;
                }
        }

        return FALSE;
}

void insert(char *s)
{
        if (search(s) == FALSE) {
                int num = hash(s);
                struct file *new_node = malloc(sizeof (struct file));
                strcpy(new_node->name, s);
                if (files[num] == NULL) {
                        files[num] = new_node;
                        files[num]->next = NULL;
                } else {
                        new_node->next = files[num];
                        files[num] = new_node;
                }
        }

        return;
}

void free_node(struct file *p)
{
        free(p);

        return;
}


void del_node(char *s)
{
        if (search(s) == TRUE) {
                struct file *p = files[hash(s)], *q;
                if (strcmp(p->name, s) == 0) {
                        q = p;
                        files[hash(s)] = p->next;
                        free_node(q);
                } else {
                        while (p != NULL) {
                                q = p;
                                p = p->next;
                                if (strcmp(p->name, s) == 0)
                                        free_node(q);
                        }
                }
        }

        return;
}


void del(int num)
{
        struct file *p =files[num], *q;
        while (p != NULL) {
                q = p;
                p = p->next;
                free(q);
        }

        return;
}

void destroy(void)
{
        int i;

        for (i = 0; i < HASHSIZE; i++)
                del(i);

        return;
}

void show(int num)
{
        struct file *p = files[num];
        if (p != NULL) {
                printf("For file begins with '%c': \n", num + 'a');
                while (p != NULL) {
                        printf("%s\n", p->name);
                        p = p->next;
                }
                printf("\n");
        }



}

void show_all(void)
{
        int i;
        for (i = 0; i < HASHSIZE; i++)
                show(i);

        return;
}

int main(void)
{
        char * file_name[] = {
                "apple", "because", "song", "Dan", "discuz", "cartoon",
                "nobody", "android", "information", "love", "like", "No",
                "nothing", "like", "alone", "nothing", "sizeof", "Yes",
        };

        int len = sizeof file_name / sizeof (char *);
        int i;
        for (i = 0; i < len; i++)
                insert(file_name[i]);
        show_all();

        printf("---------------------------------\n");
        del_node("like");
        show_all();
        destroy();

        return 0;
}

继续阅读

printf 打印颜色

引言: 控制字符的通用格式如下:

Esc[{attr1};…;{attrn}m
其中: Esc 是转义字符, 其值为”\033″;
[ 是常量的左中括号;
{attr1};…{attrn} 是若干属性, 通常是由一个有特定意义的数字代替, 每个属性之间用分号分隔;
m 就是字面常量字符m, 结束标志

属性列表如下:
>>1. 通用格式控制:
0 重置所有属性
1 高亮/加粗
2 暗淡
4 下划线
5 闪烁
7 反转
8 隐藏

>>2. 前景色:
30 黑色
31 红色
32 绿色
33 黄色
34 蓝色
35 品红
36 青色
37 白色

>>3. 背景色:
40 黑色
41 红色
42 绿色
43 黄色
44 蓝色
45 品红
46 青色
47 白色
头文件1:

/* font color */
#define NONE            "\e[0m"         /* default */
#define BLACK           "\e[0;30m"      /* black */
#define L_BLACK         "\e[1;30m"      /* light black */
#define RED             "\e[0;31m"      /* red */
#define L_RED           "\e[1;31m"      /* light red */
#define GREEN           "\e[0;32m"      /* green */
#define L_GREEN         "\e[1;32m"      /* light green */
#define BROWN           "\e[0;33m"      /* brown */
#define YELLOW          "\e[1;33m"      /* yellow */
#define BLUE            "\e[0;34m"      /* blue */
#define L_BLUE          "\e[1;34m"      /* light blue */
#define PURPLE          "\e[0;35m"      /* purple */
#define L_PURPLE        "\e[1;35m"      /* light purple */
#define CYAN            "\e[0;36m"      /* cyan */
#define L_CYAN          "\e[1;36m"      /* light_cyan */
#define GRAY            "\e[0;37m"      /* gray */
#define WHITE           "\e[1;37m"      /* white */

/* background color*/
#define BG_BLACK        "\e[40m"        /* black background */
#define BG_RED          "\e[41m"        /* red background */
#define BG_GREEN        "\e[42m"        /* green background */
#define BG_YELLOW       "\e[43m"        /* yellow background */
#define BG_BLUE         "\e[44m"        /* blue background */
#define BG_CYAN         "\e[45"         /* cyan background */
#define BG_L_CYAN       "\e[46"         /* light cyan background */
#define BG_WHITE        "\e[47"         /* white background */

/* font attribure */
#define BOLD            "\e[1m"         /* blod/light */
#define UNDERLINE       "\e[4m"         /* underline */
#define BLINK           "\e[5m"         /* blink */
#define REVERSE         "\e[7m"         /* reverse */
#define HIDE            "\e[8m"         /* hide */
#define CLEAR           "\e[2J"         /* clear */
#define CLRLINE         "\r\e[K"        //or "\e[1K\r clear line "

头文件2:

/* cprint.h
 * color print
 */

/* font attribute */
#define NONE            "\e[0m"         /* defaults */
#define BOLD            "\e[1m"         /* blod */
#define H_BRIGHT        "\e[2m"         /* half-bright */
#define UNDERLINE       "\e[4m"         /* underscore */
#define BLINK           "\e[5m"         /* blink */
#define REVERSE         "\e[7m"         /* reverse video */
#define HIDE            "\e[8m"         /* hide */
#define DOUBLE_UNDERLINE "\e[21m"       /* doubly underline */
#define INTERSITY       "\e[22m"        /* intensity */
#define UNDERLINE_OFF   "\e[24m"        /* underline off */
#define BLINK_OFF       "\e[25m"        /* blink off */
#define REVERSE_OFF     "\e[27m"        /* reverse video off */
#define CLEAR           "\e[2j"         /* clear */
#define CLRLINE         "\r\e[k"        /* or "\e[1k[r clear line" */

/* foreground color */
#define BLACK           "\e[30m"        /* black foreground */
#define RED             "\e[31m"        /* red foreground */
#define GREEN           "\e[32m"        /* green foreground */
#define BROWN           "\e[33m"        /* brown foreground */
#define YELLOW          "\e[33m"
#define BLUE            "\e[34m"        /* blue foreground */
#define MAGENTA         "\e[35m"        /* magenta foreground */
#define CYAN            "\e[36m"        /* cyan foreground */
#define WHITE           "\e[37m"        /* white foreground */
#define COLOR           "\e[39m"        /* default foreground */

/* background color*/
#define BG_BLACK        "\e[40m"        /* black background */
#define BG_RED          "\e[41m"        /* red background */
#define BG_GREEN        "\e[42m"        /* green background */
#define BG_BROWN        "\e[43m"        /* brown background */
#define BG_YELLOW       "\e[43m"
#define BG_BLUE         "\e[44m"        /* blue background */
#define BG_MAGENTA      "\e[45m"        /* magenta background */
#define BG_CYAN         "\e[46m"        /* cyan background */
#define BG_WHITE        "\e[47m"        /* white background */
#define BG_COLOR        "\e[49m"        /* defaulte background */

正文, 如何使用printf函数在控制台彩色打印

转义序列以控制字符’ESC’开头。该字符的ASCII码十进制表示为27,十六进制表示为0x1B,八进制表示为033。多数转义序列超过两个字符,故通常以’ESC’和左括号'[‘开头。该起始序列称为控制序列引导符(CSI,Control Sequence Intro),通常由’\033[‘或’\e[‘代替。
继续阅读

给linux配置虚拟内存swap交换页

1.新建swap交换页文件:

首先转到root用户,Ubuntu用户请直接在下面命令前加”su ”

dd if=/dev/zero of=/swapfile bs=1024k count=1024

dd:利用/dev/zero文件创建文件/swapfile,文件大小为1024*1024K【bs表示每一块的大小,count表示有多少快】

2.将文件创建为swap文件

mkswap /swapfile

3.启动swap

swapon /swapfile

4.设置开机启动swap空间

vi /etc/fstab

编辑fstab文件,在文件末尾添加如下命令

LABEL=SWAP-FILES /swapfile swap default 0 0

5.删除swap分区

swapoff /swapfile

rm -f /swapfile

6.从fstab中移出开机启动swap空间配置

删除/etc/stab文件中相应的行即可。

CentOS 6下VNC 配置方法

VNC是一款优秀的远程控制工具

  VNC是一款优秀的远程控制工具软件,由著名的AT&T的欧洲研究实验室开发的。VNC是在基于UNIX和Linux操作系统的免费的开放源码软件,远程控制能力强大,高效实用,其性能可以和Windows和MAC中的任何远程控制软件媲美。

  首先是安装了 CentOS 6.0 的 64 位版。本文讲解的是一种方法。VNC 配置网上搜了有很多,但是貌似写的都不够基础,这里仔细按步骤记录一下。

一、安装 VNC

  首先检查一下本机是否安装了 VNC,默认情况下,CentOS 6.0 是没有安装的。

  检查是否安装,输入:

[root@localhost ~]# rpm -q vnc vnc-server

  得到:

package vnc is not installed

package vnc-server is not installed

  提示没有安装,那么就开始安装,输入:

[root@localhost ~]# yum install vnc vnc-server

  注:如果是 Ubuntu 则输入:

[root@localhost ~]# apt-get install vnc vnc-server

  在一串指令提示后,会让你确认一些选项,输入两次 “Y” 并确认,稍作等待,提示 “Complete!” 即完成安装。

二、设置 VNC 密码

  启动 VNC,输入:

[root@localhost ~]# vncserver

  此时会提示你输入密码,因为是第一次配置。重复输入两次即可。
继续阅读