| vector<T> v1; | 保存类型为 T 对象。默认构造函数 v1 为空。 |
| vector<T> v2(v1); | v2 是 v1 的一个副本。 |
| vector<T> v3(n, i); | v3 包含 n 个值为 i 的元素。 |
| vector<T> v4(n); | v4 含有值初始化的元素的 n 个副本。 |
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<int> a;
std::vector<int> b(a);
std::vector<int> c(10, 23);
std::vector<std::string> svec(10, "null");
std::vector<std::string> svec2(10, "hi!");
std::vector<std::string> svec3(10);
return 0;
}
v.push_back(t)
Adds element with value t to end of v在 v 的末尾增加一个值为 t 的元素。以下为例子:
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
int main()
{
// read 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!
#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;
}
Please input the text: in the vector. transform each word into uppercase letters. Print the transformed elements from the vector, printing eight words to a line. INPUTOVER IN THE VECTOR TRANSFORM EACH WORD INTO UPPERCASE LETTERS PRINT THE TRANSFORMED ELEMENTS FROM THE VECTOR PRINTING EIGHT WORDS TO A LINE
vector<int> myVec;
myVec.reserve( 100 ); // 新元素还没有构造,
// 此时不能用[]访问元素
for (int i = 0; i < 100; i++ )
...{
myVec.push_back( i ); //新元素这时才构造
}
myVec.resize( 102 ); // 用元素的默认构造函数构造了两个新的元素
myVec[100] = 1; //直接操作新元素
myVec[101] = 2;
void resize(size_type new_size)
{
resize(new_size, T());
}
void resize(size_type new_size, const T& x)
{
if (new_size < size())
erase(begin() + new_size, end()); // erase区间范围以外的数据,确保区间以外的数据无效
else
insert(end(), new_size - size(), x); // 填补区间范围内空缺的数据,确保区间内的数据有效
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有