首先对于vector的赋值方法总结:
1.定义时赋值
1.vector<类型> name(地址,地址);
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s[] = {"wo","shi","zui","bang","de"};
vector<string> ex1(s, s + 5); //注意从第一个地址到最后一个地址+1
for (auto item : ex1)
{
cout << item << " ";
}
cout << endl;
return 0;
}

2.vector<类型> name1(name2);
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s[] = {"wo","shi","zui","bang","de"};
vector<string> ex1(s, s + 5);
vector<string> ex2(ex1); //将ex1赋值给ex2
for (auto item : ex2)
{
cout << item << " ";
}
cout << endl;
return 0;
}

3.vector<类型> name={};
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s[] = {"wo","shi","zui","bang","de"};
vector<string> ex1={ "wo","shi","zui","bang","de" }; //和数组一样
// vector<string> ex2(ex1);
for (auto item : ex1)
{
cout << item << " ";
}
cout << endl;
return 0;
}

2.定义后赋值
相同类型的vector直接赋值
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s[] = {"wo","shi","zui","bang","de"};
vector<string> ex1={ "wo","shi","zui","bang","de" };
vector<string> ex2;
ex2 = ex1; //将ex1赋值给已经定义之后的ex2
for (auto item : ex2)
{
cout << item << " ";
}
cout << endl;
return 0;
}
小研究
#include<iostream>
#include<vector>
using namespace std;
namespace zhx {
int a=6;
struct student
{
vector<char> name;
int age;
};
}
int main()
{
cout << zhx::a << endl;
using zhx::student;
student x;
x.age = 19;
char name[20] = "xu yu xiang";
vector<char> temp(name, name + 10);
x.name = temp;
for (auto item : temp)
{
cout << item<<" ";
}
cout << endl;
for (auto item : x.name)
{
cout << item << " ";
}
cout << endl;
return 0;
}

✳
谢谢你读到这里。
更新于 2022-07-02