实例代码:
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include <array>
using namespace std;
namespace _nmsp1
{
void func()
{
return;
}
}
namespace _nmsp2
{
void func()
{
array<string, 5> mystring = { "I", "Love1Love2Love3Love4Love5Love6Love7", "China" };
cout << "myString.size() = " << mystring.size() << endl;
mystring[0] = "It is very long~~~~~~~~~~~~~long~~~~~~~~~~~~long";
mystring[4] = "It is very long~~~~~~~~~~~~~long~~~~~~~~~~~~long";
cout << "sizeof(string) = " << sizeof(string) << endl;
for (size_t i = 0; i < mystring.size(); ++i)
{
const char *p = mystring[i].c_str();
cout << "-----------------begin---------------------" << endl;
cout << "数组元素值= " << p << endl;
printf("对象地址=%p\n", &mystring[i]);
printf("指向的字符串地址=%p\n", p);
cout << "-----------------end---------------------" << endl;
}
const char *p1 = "Love1Love2Love3Love4Love5Love6Love7";
const char *p2 = "Love1Love2Love3Love4Love5Love6Love7";
printf("p1地址=%p\n", p1);
printf("p2地址=%p\n", p2);
}
}
namespace _nmsp3
{
class A
{
public:
int m_i;
A(int tmpv) :m_i(tmpv)
{
cout << "A::A()构造函数执行" << endl;
}
A(const A& tmpA)
{
m_i = tmpA.m_i;
cout << "A::A()拷贝构造函数执行" << endl;
}
~A()
{
cout << "A::~A()析构函数执行" << endl;
}
};
void func()
{
vector<A> myveca;
cout << "myveca.capacity() = " << myveca.capacity() << endl;
cout << "myveca.size() = " << myveca.size() << endl;
myveca.reserve(10);
cout << "myveca.capacity() = " << myveca.capacity() << endl;
cout << "myveca.size() = " << myveca.size() << endl;
for (int i = 0; i < 5; ++i)
{
cout << "-----------begin-------------" << endl;
cout << "容器插入元素之前size=" << myveca.size() << endl;
cout << "容器插入元素之前capacity=" << myveca.capacity() << endl;
myveca.push_back(A(i));
cout << "容器插入元素之后size=" << myveca.size() << endl;
cout << "容器插入元素之后capacity=" << myveca.capacity() << endl;
cout << "-----------end---------------" << endl;
}
cout << "--------------------------------------------------------" << endl;
for (int i = 0; i < 5; ++i)
{
printf("下标为%d的元素的地址是%p,m_i=%d\n", i, &myveca[i], myveca[i].m_i);
}
cout << "---------------------------------删除一个元素看看-----------------------" << endl;
int icount = 0;
for (auto pos = myveca.begin(); pos != myveca.end(); ++pos)
{
icount++;
if (icount == 2)
{
myveca.erase(pos);
break;
}
}
for (int i = 0; i < 4; ++i)
{
printf("下标为%d的元素的地址是%p,m_i=%d\n", i, &myveca[i], myveca[i].m_i);
}
{
cout << "---------------------------------插入一个元素看看-----------------------" << endl;
int icount = 0;
for (auto pos = myveca.begin(); pos != myveca.end(); ++pos)
{
icount++;
if (icount == 2)
{
myveca.insert(pos, A(10));
break;
}
}
}
for (int i = 0; i < 5; ++i)
{
printf("下标为%d的元素的地址是%p,m_i=%d\n", i, &myveca[i], myveca[i].m_i);
}
}
}
int main()
{
_nmsp3::func();
return 1;
}