vector<string> strArray(10);
strArray[0] = "hello";
strArray[1] = "world";
strArray[2] = "this";
strArray[3] = "find";
strArray[4] = "gank";
strArray[5] = "pink";
strArray[6 ]= "that";
strArray[7] = "when";
strArray[8] = "how";
strArray[9] = "cpp";
有没有更好的初始化方式?
7 个解决方案
#1
strArray.push_back("hello");
……
……
#2
string str[n]={"hello", ...};
vector<string> strArray(str,str+n);
#3
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string str[]={"hello", "world", "\n"};
vector<string> strArray(str,str+sizeof(str)/sizeof(str[0]));
return 0;
}
#4
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
const char* init[]=
{
"A","B","C"
};
vector<string> strArray(init,init+3);
for(vector<string>::iterator iter=strArray.begin();iter!=strArray.end();++iter)
{
cout<<*iter<<" ";
}
cout<<endl;
return 0;
}
这样就可以了,话说string有接受const char*的构造函数,构造之后再placement new.
#5
push_back
#6
vector<string> strArray(10,"hello");
#7
string str[]={"hello","world","this","find","gank","pink","that","when","how","cpp"};
vector<string> strArray(str,str+10);
#1
strArray.push_back("hello");
……
……
#2
string str[n]={"hello", ...};
vector<string> strArray(str,str+n);
#3
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string str[]={"hello", "world", "\n"};
vector<string> strArray(str,str+sizeof(str)/sizeof(str[0]));
return 0;
}
#4
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
const char* init[]=
{
"A","B","C"
};
vector<string> strArray(init,init+3);
for(vector<string>::iterator iter=strArray.begin();iter!=strArray.end();++iter)
{
cout<<*iter<<" ";
}
cout<<endl;
return 0;
}
这样就可以了,话说string有接受const char*的构造函数,构造之后再placement new.
#5
push_back
#6
vector<string> strArray(10,"hello");
#7
string str[]={"hello","world","this","find","gank","pink","that","when","how","cpp"};
vector<string> strArray(str,str+10);