我试图阻止矢量的最后一项打印。如何修改我的代码才能实现这一目标?
void lAverage(){
cout << endl << "The average of: ";
for (int i = 0; i < gAverage.size(); ++i){
if (i == gAverage.size()) {
cout << gAverage[i]; // I have to modify something here.
} else{
cout << gAverage[i] << ", ";
}
}
cout << " = " << average << endl;
}
而不是打印:平均值:3,2,1,0 = 2
我宁愿:平均值:3,2,1 = 2
最后一个没有逗号,0被删除。
答案 0 :(得分:1)
请稍早停止迭代:
int size = gAverage.size() - 1;
for (int i = 0; i < size; ++i){
if (i == size - 1) {
cout << gAverage[i];
} else{
cout << gAverage[i] << ", ";
}
}
cout << " = " << average << endl;
答案 1 :(得分:1)
没有
的情况(i == gAverage.size())
因为我总是小于gAverage.size()因为 for循环的范围是从0 ..到gAverage.size() - 1
你应该检查
if (i == gAverage.size()-1)
答案 2 :(得分:1)
如果要打印到带有插入逗号的输出流,但同时排除容器中的最后两项(无论出于何种原因),这里是使用std::copy
算法的解决方案:
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;
void lAverage()
{
// make sure there are at least 2 items
if (gAverage.size() >= 2)
{
auto itLast = gAverage.end() - 2;
cout << endl << "The average of: ";
// copy item to output stream with intervening comma up until
// two before the last item
copy(gAverage.begin(), itLast, ostream_iterator<int>(cout, ","));
// print the item before the last and the average
cout << *itLast << " = " << average << endl;
}
}
答案 3 :(得分:0)
您需要迭代,直到到达最后一个元素之前的元素:
for (int i = 0; i < gAverage.size()-1; ++i){
和
if (i == gAverage.size()-2) {
小心,它是 -2 ,因为你永远不会到达gAverage.size()-1
答案 4 :(得分:0)
这里有两个问题:如何打印一个小于容器总数的元素,以及如何打印最后一个元素后面不跟逗号。
为了在不使用条件的情况下满足这两个要求,我将停止循环两个元素
int last = gAverage.size() - 2;
for (int i = 0; i < last; ++i)
{
cout << gAverage[i] << ", ";
}
cout << gAverage[last];
cout << " = " << average << endl;
循环打印逗号后面的所有值。下一个cout
语句打印数组的倒数第二个元素。
这可以避免循环中条件的愚蠢,以检测最后打印的元素。