GoldenLee
GoldenLee

Reputation: 747

How to get a string of union set from a vector string?

I have a vector string filled with some file extensions as follows:

vector<string> vExt;
vExt.push_back("*.JPG;*.TGA;*.TIF");
vExt.push_back("*.PNG;*.RAW");
vExt.push_back("*.BMP;*.HDF");
vExt.push_back("*.GIF");
vExt.push_back("*.JPG");
vExt.push_back("*.BMP");

I now want to get a string of union set from the above-mentioned vector string, in which each file extension must be unique in the resulting string. As for my given example, the resulting string should take the form of "*.JPG;*.TGA;*.TIF;*.PNG;*.RAW;*.BMP;*.HDF;*.GIF".

I know that std::unique can remove consecutive duplicates in range. It con't work with my condition. Would you please show me how to do that? Thank you!

Upvotes: 1

Views: 665

Answers (3)

sehe
sehe

Reputation: 393719

See it live here: http://ideone.com/0fmy0 (FIXED)

#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <set>

int main()
{
    std::vector<std::string> vExt;
    vExt.push_back("*.JPG;*.TGA;*.TIF");
    vExt.push_back("*.PNG;*.RAW");
    vExt.push_back("*.BMP;*.HDF");
    vExt.push_back("*.GIF");
    vExt.push_back("*.JPG");
    vExt.push_back("*.BMP");

    std::stringstream ss;
    std::copy(vExt.begin(), vExt.end(),
            std::ostream_iterator<std::string>(ss, ";"));

    std::string element;
    std::set<std::string> unique;
    while (std::getline(ss, element, ';'))
        unique.insert(unique.end(), element);

    std::stringstream oss;

    std::copy(unique.begin(), unique.end(),
            std::ostream_iterator<std::string>(oss, ";"));

    std::cout << oss.str() << std::endl;

    return 0;
}

output:

*.BMP;*.GIF;*.HDF;*.JPG;*.PNG;*.RAW;*.TGA;*.TIF;

Upvotes: 4

pmr
pmr

Reputation: 59841

You need to parse the strings that contain multiple file extensions and then push them into the vector. After that std::unique will do what you want. Have a look at the Boost.Tokenizer class, that should make this trivial.

Upvotes: 0

NPE
NPE

Reputation: 500873

I'd tokenize each string into constituent parts (using semicolon as the separator), and stick the resulting tokens into a set. The resultant contents of that set is what you're looking for.

Upvotes: 1

Related Questions