2015.08.28 C++笔记

string

 

using namespace::name;
//其中namespace为命名空间,多为std;name为命名空间中的名字,如cin,cout,endl,string等

string s1; 默认构造函数 s1 为空串
string s2(s1); 将 s2 初始化为 s1 的一个副本
string s3("value"); 将 s3 初始化为一个字符串字面值副本
string s4(n, 'c'); 将 s4 初始化为字符 'c' 的 n 个副本

string不能使用 string s5(n)的形式初始化,而vector可以

 

s.empty() 如果 s 为空串,则返回 true,否则返回 false。
s.size() 返回 s 中字符的个数

#include <cctype>
isalnum(c) 如果 c 是字母或数字,则为 True。
isalpha(c) 如果 c 是字母,则为 true。
iscntrl(c) 如果 c 是控制字符,则为 true
isdigit(c) 如果 c 是数字,则为 true。
isgraph(c) 如果 c 不是空格,但可打印,则为 true。
islower(c) 如果 c 是小写字母,则为 true。
isprint(c) 如果 c 是可打印的字符,则为 true。
ispunct(c) 如果 c 是标点符号,则 true。
isspace(c) 如果 c 是空白字符,则为 true。
isupper(c) 如果 c 是大写字母,则 true。
isxdigit(c) 如果是 c 十六进制数,则为 true。
tolower(c) 如果 c 大写字母,返回其小写字母形式,否则直接返回 c。
toupper(c) 如果 c 是小写字母,则返回其大写字母形式,否则直接返回 c。
//对string中的字符进行处理

 

template


template<class 形参名>
  返回类型 函数名 (参数列表)
  { }
//一但声明了模板函数就可以用模板函数的形参名声明函数中的变量,即可以在该函数中使用内置类型的地方都可以使用模板形参名。
//当调用这样的模板函数时类型T就会被被调用时的类型所代替,比如swap(a,b)其中a和b是int 型,这时模板函数swap中的形参T就会被int 所代替,模板函数就变为swap(int &a, int &b)。

template<class 形参名>
  class 类名
  {
     形参名 node;
  };
//一但声明了类模板就可以用类模板的形参名声明类中的成员变量和成员函数,即可以在类中使用内置类型的地方都可以使用模板形参名来声明。
template<class T>
  class A
  {
    public:
     T a; T b;
     T hy(T c, T &d);
  };

 

vector


vector<T> v1; vector 保存类型为 T 对象。
默认构造函数 v1 为空。
vector<T> v2(v1); v2 是 v1 的一个副本。
vector<T> v3(n, i); v3 包含 n 个值为 i 的元素。
vector<T> v4(n); v4 含有值初始化的元素的 n 个副本;如果是int则默认为0。

// read words from the standard input and store them as elements in
a vector
string word;
vector<string> text; // empty vector
133
while (cin >> word) {
text.push_back(word); // append word to text
}

 

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace::std;

int main()
{
//	string b;
//	cout << b[0] << endl;

	string s("Hello World!!!");
	string::size_type punct_cnt = 0;
	// count number of punctuation characters in s
	for (string::size_type index = 0; index != s.size(); ++index)
		if (ispunct(s[index]))
			++punct_cnt;
	cout << punct_cnt<< " punctuation characters in " << s << endl;

	// convert s to lowercase
	for (string::size_type index = 0; index != s.size(); ++index)
		s[index] = tolower(s[index]);
	cout << s << endl;
	
	string a(10,'*');
	cout<<"\n"<<a<<endl;

	a="test.txt";
	ifstream F(a);
	if(!F)
	{
		cout<<"ERROR!"<<endl;
		getchar();
	}
	char c, buff[20];
	while (!F.eof())
	{
		F>>c;
		if (c>='A'&&c<='z')
		{
			F.getline(buff,20);
			cout<<c<<buff<<endl;
		}
	}
	cout<<endl;

	// read words from the standard input and store them as elements ina vector
	string word;
	vector<string> text; // empty vector133
	do
	{
	while (cin >> word) 
	{
		text.push_back(word); // append word to text
		if (word == "end") break;
	}
	int size = text.size();
	cout<<"\nnumber of input words is "<<size<<endl;
	for ( int i=0; i<size; i++)
	{
		cout<<text[i]<<endl;
	}
	}
	while(true);
	return 0;
}

 

posted @ 2015-08-28 21:48  王爪爪  阅读(140)  评论(0编辑  收藏  举报