Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

vector - Removing a comma from a c++ output

I wrote this program that sorts numbers in vectors from greatest to least, it works great but the only thing that is bugging me is trying to remove the comma from the last number. Heres my code

#include <iostream>
#include <vector>
#include <cstdlib>
#include <algorithm>
using namespace std;

int main() {

    vector<int> vi1, vi2, vi3;
    srand(987);

    for (int i = 0; i < 10; ++i) vi1.push_back(rand() % 10);
    sort(vi1.begin(), vi1.end());

    for (int i = 0; i < 10; ++i) vi2.push_back(rand() % 10);
    sort(vi2.begin(), vi2.end())

    while(!vi1.empty() && !vi2.empty()) {
        if(vi1.back()>=vi2.back()) {
            vi3.push_back(vi1.back());
            vi1.pop_back();
        }
        else {
            vi3.push_back(vi2.back());
            vi2.pop_back();
        }
    }

    while(!vi1.empty()) {
        vi3.push_back(vi1.back());
        vi1.pop_back();
    }
    while(!vi2.empty()) {
        vi3.push_back(vi2.back());
        vi2.pop_back();
    }

    for (auto i = vi3.begin(); i != vi3.end(); ++i)
        cout << *i << ", ";
    cout << "
Bye..." << endl;
    return 0;
}

and here is the output

9, 9, 9, 8, 8, 8, 6, 6, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 
Bye...

as you can see after the last 0 there is a comma which doesn't make sense grammatically speaking. How can I remove that comma?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Rather than removing the simplest way is just to print commas only for other values than the first:

for (auto i = vi3.begin(); i != vi3.end(); ++i) {
    if(i != vi3.begin()) {
        cout << ", ";
    }
    cout << *i;
}

I am using this idiom regularly to format e.g. SQL parameter lists, or similar where a delimiter isn't wanted after the last element but for any others.
There are other ways to detect the first element (e.g. using a bool variable initialized to true before the loop starts, and set to false upon the first iteration).
For your example it seems just checking for vi3.begin() is the easiest and most natural way.

Here's the generic variant in pseudo code:

bool isFirstOutput = true;
for_each(element in list) {
    if(not isFirstOutput) {
        print delimiter;
    }
    print element;
    isFirstOutput = false;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...