GoldenLee
GoldenLee

Reputation: 747

Selectively populated vectors with substrings extracted from a source string

I have a char array, in which its contents look something like the following:

char buffer[] = "I1 I2 V1 V2 I3 V3 I4 DO V4";

As you may see, it's a typical blank separated character string. I want to put all sub-string(s) starting with a letter "I" into a vector (IVector), and sort its elements in ascending order. At the same time, I'd also want to put all sub-string(s) starting with a letter "V" into another vector (VVector), and sort its elements in ascending order. The other(s) (e.g. "DO" in this example) will be ignored.

I'm not familiar with STL algorithm library. Are there any functions to help me achieve the avove-mentioned job?

Thank you!

Upvotes: 2

Views: 114

Answers (2)

Björn Pollex
Björn Pollex

Reputation: 76876

You can iterate over all the substrings using an std::istream_iterator<std::string>:

std::stringstream s(buffer);
std::istream_iterator<std::string> begin(s);
std::istream_iterator<std::string> end;
for( ; begin != end; ++begin) {
    switch((*begin)[0]) { // switch on first character 
        // insert into appropriate vector here
    }
}

Then you can use std::sort to sort the vectors, as @Billy has already pointed out. You could also consider using an std::set, as that will always keep your items sorted in the first place.

Upvotes: 2

Billy ONeal
Billy ONeal

Reputation: 106609

Are there any functions to help me achieve the avove-mentioned job?

Yes. Have a look at std::find and std::sort.

Upvotes: 1

Related Questions