矢量大小:2
矢量数据:Carol Mary
if(vector.size() >=2)
{
cout<<vector.size();
for(int i=1;i<vector.size()-2;i++)
{
cout<<" AND ";
}
}
输出显示:Carol AND Mary AND
如何将其更改为Carol AND Mary?
当我的矢量大小为3时,
如何将其更改为Carol AND Mary AND Peter
提前致谢!
答案 0 :(得分:3)
假设向量名为v。
if(!v.empty()) {
cout << v[0];
for(int i = 1; i<v.size(); ++i) {
cout << " AND " << v[i];
}
}
答案 1 :(得分:1)
我会使用我的infix_ostream_iterator
:
std::copy(vec.begin(), vec.end(),
infix_ostream_iterator<std::string>(std::cout, " AND "));
infix_ostream_iterator
代码位于CodeReview.SE。
答案 2 :(得分:1)
只是添加我喜欢的方式:
const char *sep = "";
for (size_t i=0; i<vec.size(); ++i, sep=" AND ")
cout << sep << vec[i];
cout << endl;
或者,甚至更短:
cout << join(vec, " AND ") << endl;
也就是说,使用boost :: algorithm :: join(),就像Python(" AND ".join(vec)
)一样。
答案 3 :(得分:0)
std::vector<std::string> vec {"Carol","Marry","Peter"};
int i=1;
std::cout<<vec[0];
for(;i<vec.size();++i)
std::cout<<" AND "<<vec[i];