C++中的vector容器对象学习笔记

2020-01-06 15:10:03于丽
words from the standard input and store them as elements in a vector std::string word; std::vector<std::string> text; // empty vector while (std::cin >> word) { text.push_back(word); // append word to text for(std::vector<int>::size_type ix =0; ix != text.size(); ++ix) std::cout<<"Now text["<<ix<< "]is: "<<text[ix]<<std::endl; } return 0; }

结果为:


Hello
Now text[0]is: Hello
world!
Now text[0]is: Hello
Now text[1]is: world!


注意:
1、不可以直接输出vector对象! 和list差别太大了。。。

2、下标操作可以改变已有元素:例如上例,可以在最后加上:text[0] = "elements";

3、当然和list一样,肯定不能text[100] = "elements";在Python中这样操作list回报下标越界, C++中编译不会报错,运行自动退出!【 数组操作时这个会坑死你,不会报错,不会退出!理所当然,缓冲区溢出了,黑客们太喜欢了! 】

4、由于动态增长, 不能先测试长度 ,而是循环中动态测试!否则会出现莫名其妙的BUG!有人会担心效率?别担心!代价很小【内联函数】。

v[n]

Returns element at position n in v返回 v 中位置为 n 的元素。

(1)v1 = v2[/code]

Replaces elements in v1 by a copy of elements in v2把 v1 的元素替换为 v2 中元素的副本。

(2)v1 == v2[/code]

Returns true if v1 and v2 are equal如果 v1 与 v2 相等,则返回 true。

(3)!=, <, <=,>, and >=

Have their normal meanings保持这些操作符惯有的含义。

一个简单的例子

读入一段文本到 vector 对象,每个单词存储为 vector 中的一个元素。把vector 对象中每个单词转化为大写字母。输出 vector 对象中转化后的元素,每八个单词为一行输出。

假设文本为:in the vector. transform each word into uppercase letters. Print the transformed elements from the vector, printing eight words to a line.


#include <iostream>
#include <string>
#include <vector>

std::string deal_word(std::string word)
{
 std::string WORD; // 创建空字符串
 for(std::string::size_type ix =0; ix != word.size(); ++ix)
 {
 if (not ispunct(word[ix]))
 {
  WORD += toupper(word[ix]); //连接非标点字符到字符串
 }
 }
 return WORD;
}

int main()
{
 std::string word; // 缓存输入的单词
 std::vector<std::string> text; // empty vector
 std::cout<<"Please input the text:"<<std::endl; //提示输入
 while (std::cin >> word and word != "INPUTOVER") // INPUTOVER 用于标示输入结束,也可以ctrl + z停止输入 
 {
 word = deal_word(word); // 单词处理
 text.push_back(word); // append word to text
 }
 for(std::vector<int>::size_type ix =0, j = 0; ix != text.size(); ++ix, ++j)
 {
 if (j==8) // 8个单词一行
 {
  std::cout<<std::endl; //换行
  j = 0; //重新计数
 }
  std::cout<<text[ix]<<" "; //加空格!
 }
 return 0;
}