C++ Primer_3 字符串、向量和数组

来源:互联网 发布:怎么在淘宝上开个网店 编辑:程序博客网 时间:2024/06/03 20:45

3.1 命名空间的using声明

using声明具有如下的形式:

    using namespace::name;   // 一旦声明了上述语句,就可以直接访问命名空间中的名字。

注意:用到的每个名字都必须有自己的声明语句,而且每句话都得以分号结束。

示例:

#include <iostream>// using declaration; when we use the name cin, we get the one from the namespace stdusing std::cin;int main(){int i;cin >> i; // ok: cin is a synonym for std::cincout << i; // error: no using declaration; we must use the full namestd::cout << i; // ok: explicitly use cout from namepsace stdreturn 0;}


3.2 标准库类型string

标准库类型string表示可变长的字符序列,使用string类型必须首先包含string头文件。作为标准库的一部分,string定义在命名空间std中。

定义和初始化string对象

    

string对象上的操作

 

读写string对象:

int main(){string s; // emptystringcin >> s; //read a whitespace-separated string into s 注意遇到空白停止cout << s<< endl; // write s to the outputreturn 0;}cin >> s1>> s2; // read first input into s1, second into s2

读取未知数量的string对象:

int main(){string word;while (cin >>word) // read until end-of-file 注意还是空格停止输入,无法输入句子cout << word<< endl; // write each word followed by a new linereturn 0;}


使用getline读取一整行:

使用getline函数可以读入空格符,遇到换行符停止。 

int main(){string line;// read input a lineat a time until end-of-filewhile (getline(cin,line))cout << line<< endl;return 0;}

string的empty和size操作:

empty函数根据string对象是否为空返回一个对应的布尔值,调用该函数只要使用点操作符指明是哪个对象执行了empty函数就可以了。

while (getline(cin,line))if (!line.empty())cout << line<< endl;

    

size函数返回string对象的长度:

string line;// read input a lineat a time and print lines that are longer than 80 characterswhile (getline(cin,line))if (line.size() >80)cout << line<< endl;


    Note: 对于所有存放string类的size函数返回值的变量,都应该是是string::size_type类型的。

 

比较string对象:

   string类定义了“== ,!=,<,<=,>,>=”运算符 逐一  比较字符串中的字母,并且对大小写敏感。

(1)如果两个string对象的长度不同,且对应字母相等,则短的小于长的;

(2)如果两个string对象在某些对应位置上不相等,则结果为第一对相异字符相比较的结果;

 

两个string对象相加:

    两个string对象相加的结果是把左侧的运算对象与右侧的运算对象串接而成。

 

字面值和string对象相加:

    必须确保“+”运算符两侧至少有一个是string对象;

 

 处理string对象中的字符

   cctype头文件中定义了一组标准库函数处理这部分工作,其中包含的函数如下:

 

使用范围for语句遍历给顶序列中的每个元素并对序列中的每个值进行某种操作:

for (declaration :expression)statementstring str("somestring");// print thecharacters in str one character to a linefor (auto c : str) //for every char in strcout << c<< endl; // print the current character followed by a newline

string s("HelloWorld!!!");// punct_cnt has thesame type that s.size returns; see § 2.5.3 (p. 70)decltype(s.size())punct_cnt = 0;// count the numberof punctuation characters in sfor (auto c : s) //for every char in sif (ispunct(c)) // ifthe character is punctuation++punct_cnt; //increment the punctuation countercout <<punct_cnt<< "punctuation characters in " << s << endl;

string s("HelloWorld!!!");// convert s touppercasefor (auto &c : s)// for every char in s (note: c is a reference)c = toupper(c); // cis a reference, so the assignment changes the charin scout << s<< endl;The output of thiscode isHELLO WORLD!!! 


只处理一部分字符:

    下标运算符[  ] 接收的输入参数是string::size_type 类型的值,这个参数表示要访问的字符的位置,返回值是该位置上字符的引用。

// process charactersin s until we run out of characters or we hit a whitespacefor(decltype(s.size()) index = 0;index != s.size()&& !isspace(s[index]); ++index)s[index] =toupper(s[index]); // capitalize the current characterThis programgeneratesSOME string

 

使用下标执行随机访问:

const stringhexdigits = "0123456789ABCDEF"; // possible hex digitscout <<"Enter a series of numbers between 0 and 15"<< "separated by spaces. Hit ENTER when finished: "<< endl;string result; //will hold the resulting hexify'd stringstring::size_type n;// hold numbers from the inputwhile (cin >>n)if (n <hexdigits.size()) // ignore invalid inputresult +=hexdigits[n]; // fetch the indicated hex digitcout <<"Your hex number is: " << result << endl;If we give thisprogram the input12 0 5 15 8 15the output will beYour hex number is:C05F8F


3.3 标准库类型vector

    标准库类型vector表示对象的集合,其中所有对象的类型都相同。集合中的每个对象都有一个对应的索引,索引用于访问对象。想要使用vector,必须包含适当的头文件。

#include <vector>using std::vector;

1. 定义和初始化vector对象



Note:注意花括号和圆括号的区别。


值初始化:

vector<int> ivec(10); // ten elements, each initialized to 0vector<string> svec(10); // ten elements, each an empty string


vector<int> v1(10); // v1 has ten elements with value 0vector<int> v2{10}; // v2 has one element with value 10vector<int> v3(10, 1); // v3 has ten elements with value 1vector<int> v4{10, 1}; // v4 has two elements with values 10 and 1 

vector<string> v5{"hi"}; // list initialization: v5 has one elementvector<string> v6("hi"); // error: can't construct a vector from a string literalvector<string> v7{10}; // v7 has ten default-initialized elementsvector<string> v8{10, "hi"}; // v8 has ten elements with value "hi"

2. 向vector对象中添加元素

    利用push_back 向其中添加元素,push_back负责把一个值当成对象的尾元素“压到”vector对象的“尾端”。

vector<int> v2; // empty vectorfor (int i = 0; i != 100; ++i)v2.push_back(i); // append sequential integers to v2// at end of loop v2 has 100 elements, values 0 . . . 99

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


3. 其他vector操作:


vector<int> v{1,2,3,4,5,6,7,8,9};for (auto &i : v) // for each element in v (note: i is a reference)i *= i; // square the element valuefor (auto i : v) // for each element in vcout << i << " "; // print the elementcout << endl;

// count the number of grades by clusters of ten: 0--9, 10--19, . .. 90--99, 100vector<unsigned> scores(11, 0); // 11 buckets, all initially 0unsigned grade;while (cin >> grade) { // read the gradesif (grade <= 100) // handle only valid grades++scores[grade/10]; // increment the counter for the current cluster}

不能用下标形式添加元素:

vector<int> ivec; // empty vectorfor (decltype(ivec.size()) ix = 0; ix != 10; ++ix)ivec[ix] = ix; // disaster: ivec has no elements

正确的方法是使用push_back !

 



0 0
原创粉丝点击