Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ check if element is std::vector

Tags:

c++

types

vector

i would like to iterate through a vector and check if elements are vectors or strings. Also i need a way to pass different vecors to a function. Something like this:

using namespace std;
string toCustomString(<some vector> vec) {
    string ret = "";
    for(size_t i = 0; i < vec.length(); ++i) 
        if (vec[i] == %vector%)
            ret += toCustomString(vec[i]);
        else //if type of vec[i] is string
            ret += "foo"+vec[i]+"bar";
    }
    return ret;
}
  • Well, first i need to know how i can check correctly if vec[i] is a std::vector

  • Then i need to know how to define the paramater for the function to accept any kind of (multidimensional) vector

like image 571
Alex Schneider Avatar asked Oct 21 '25 06:10

Alex Schneider


1 Answers

std::vector can only contain one type - that is the T in std::vector<T>, which can be accessed with the member value_type.

What you probably are looking for is template specialization:

template<typename T>
string toCustomString(std::vector<T> vec) {
    // general case
}

template<>
string toCustomString<std::string>(std::vector<std::string> vec) {
    // strings
}

(if you want to partially specialize it over all vectors then you'll need to lift it to a struct)

If you really want to store both strings and vectors in the vector then look at Boost.Variant and Boost.Any

like image 90
Pubby Avatar answered Oct 22 '25 19:10

Pubby