开发者

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

开发者 https://www.devze.com 2023-04-07 08:36 出处:网络
I have a vector string filled with some file extensions as follows: vector<string> vExt; vExt.push_back(\"*.JPG;*.TGA;*.TIF\");

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 t开发者_C百科he 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!


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;


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号