find an element in std::vector of std::anyConcatenating two std::vectorsHow to convert a std::string to const char* or char*?std::wstring VS std::stringHow to find out if an item is present in a std::vector?How do I erase an element from std::vector<> by index?Why is “using namespace std” considered bad practice?What is the easiest way to initialize a std::vector with hardcoded elements?Order a vector of points based on another vector of different size and typeComparing std::vector or std::set in this case for time complexity - More efficent?Strange behaviour of std::find, returns true when the element is not in the vector

What is the opposite of 'gravitas'?

I2C signal and power over long range (10meter cable)

For airliners, what prevents wing strikes on landing in bad weather?

How to check participants in at events?

Visiting the UK as unmarried couple

Is the next prime number always the next number divisible by the current prime number, except for any numbers previously divisible by primes?

Teaching indefinite integrals that require special-casing

How to prevent YouTube from showing already watched videos?

Is infinity mathematically observable?

Simple image editor tool to draw a simple box/rectangle in an existing image

How do ultrasonic sensors differentiate between transmitted and received signals?

Can I Retrieve Email Addresses from BCC?

"lassen" in meaning "sich fassen"

Simple recursive Sudoku solver

Organic chemistry Iodoform Reaction

Is there an Impartial Brexit Deal comparison site?

Can the electrostatic force be infinite in magnitude?

Is a naturally all "male" species possible?

What should I use for Mishna study?

A known event to a history junkie

Is there a good way to store credentials outside of a password manager?

How can I successfully establish a nationwide combat training program for a large country?

Can a Gentile theist be saved?

Have I saved too much for retirement so far?



find an element in std::vector of std::any


Concatenating two std::vectorsHow to convert a std::string to const char* or char*?std::wstring VS std::stringHow to find out if an item is present in a std::vector?How do I erase an element from std::vector<> by index?Why is “using namespace std” considered bad practice?What is the easiest way to initialize a std::vector with hardcoded elements?Order a vector of points based on another vector of different size and typeComparing std::vector or std::set in this case for time complexity - More efficent?Strange behaviour of std::find, returns true when the element is not in the vector













6















I want to check whether an element exists in the vector or not. I know the below piece of code will check it.



#include <algorithm>

if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
std::cout << "found";
else
std::cout << "not found";


But I have the vector of any type. i.e. std::vector<std::any>
I am pushing elements into vector like this.



std::vector<std::any> temp;
temp.emplace_back(std::string("A"));
temp.emplace_back(10);
temp.emplace_back(3.14f);


So I need to find whether string "A" present in the vector or not. Can std::find help here?



As of now I am using below piece of code to do this



bool isItemPresentInAnyVector(std::vector<std::any> items, std::any item)

for (const auto& it : items)

if (it.type() == typeid(std::string) && item.type() == typeid(std::string))

std::string strVecItem = std::any_cast<std::string>(it);
std::string strItem = std::any_cast<std::string>(item);

if (strVecItem.compare(strItem) == 0)
return true;

else if (it.type() == typeid(int) && item.type() == typeid(int))

int iVecItem = std::any_cast<int>(it);
int iItem = std::any_cast<int>(item);

if (iVecItem == iItem)
return true;

else if (it.type() == typeid(float) && item.type() == typeid(float))

float fVecItem = std::any_cast<float>(it);
float fItem = std::any_cast<float>(item);

if (fVecItem == fItem)
return true;



return false;










share|improve this question



















  • 2





    Read std::find_if.

    – Passer By
    Mar 8 at 6:51






  • 6





    Have you considered using std::variant<int, float, std::string> instead? std::find will work fine on that.

    – Eric
    Mar 8 at 6:57











  • Generic comparisons of std::any would require support from any itself (since you can't any_cast based on type(), which is not known at compile time); For what you seem to be doing, variant is indeed better along multiple dimensions - no extra heap overhead, no hidden virtual dispatch, etc...

    – Stefan Atev
    Mar 8 at 15:58















6















I want to check whether an element exists in the vector or not. I know the below piece of code will check it.



#include <algorithm>

if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
std::cout << "found";
else
std::cout << "not found";


But I have the vector of any type. i.e. std::vector<std::any>
I am pushing elements into vector like this.



std::vector<std::any> temp;
temp.emplace_back(std::string("A"));
temp.emplace_back(10);
temp.emplace_back(3.14f);


So I need to find whether string "A" present in the vector or not. Can std::find help here?



As of now I am using below piece of code to do this



bool isItemPresentInAnyVector(std::vector<std::any> items, std::any item)

for (const auto& it : items)

if (it.type() == typeid(std::string) && item.type() == typeid(std::string))

std::string strVecItem = std::any_cast<std::string>(it);
std::string strItem = std::any_cast<std::string>(item);

if (strVecItem.compare(strItem) == 0)
return true;

else if (it.type() == typeid(int) && item.type() == typeid(int))

int iVecItem = std::any_cast<int>(it);
int iItem = std::any_cast<int>(item);

if (iVecItem == iItem)
return true;

else if (it.type() == typeid(float) && item.type() == typeid(float))

float fVecItem = std::any_cast<float>(it);
float fItem = std::any_cast<float>(item);

if (fVecItem == fItem)
return true;



return false;










share|improve this question



















  • 2





    Read std::find_if.

    – Passer By
    Mar 8 at 6:51






  • 6





    Have you considered using std::variant<int, float, std::string> instead? std::find will work fine on that.

    – Eric
    Mar 8 at 6:57











  • Generic comparisons of std::any would require support from any itself (since you can't any_cast based on type(), which is not known at compile time); For what you seem to be doing, variant is indeed better along multiple dimensions - no extra heap overhead, no hidden virtual dispatch, etc...

    – Stefan Atev
    Mar 8 at 15:58













6












6








6








I want to check whether an element exists in the vector or not. I know the below piece of code will check it.



#include <algorithm>

if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
std::cout << "found";
else
std::cout << "not found";


But I have the vector of any type. i.e. std::vector<std::any>
I am pushing elements into vector like this.



std::vector<std::any> temp;
temp.emplace_back(std::string("A"));
temp.emplace_back(10);
temp.emplace_back(3.14f);


So I need to find whether string "A" present in the vector or not. Can std::find help here?



As of now I am using below piece of code to do this



bool isItemPresentInAnyVector(std::vector<std::any> items, std::any item)

for (const auto& it : items)

if (it.type() == typeid(std::string) && item.type() == typeid(std::string))

std::string strVecItem = std::any_cast<std::string>(it);
std::string strItem = std::any_cast<std::string>(item);

if (strVecItem.compare(strItem) == 0)
return true;

else if (it.type() == typeid(int) && item.type() == typeid(int))

int iVecItem = std::any_cast<int>(it);
int iItem = std::any_cast<int>(item);

if (iVecItem == iItem)
return true;

else if (it.type() == typeid(float) && item.type() == typeid(float))

float fVecItem = std::any_cast<float>(it);
float fItem = std::any_cast<float>(item);

if (fVecItem == fItem)
return true;



return false;










share|improve this question
















I want to check whether an element exists in the vector or not. I know the below piece of code will check it.



#include <algorithm>

if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
std::cout << "found";
else
std::cout << "not found";


But I have the vector of any type. i.e. std::vector<std::any>
I am pushing elements into vector like this.



std::vector<std::any> temp;
temp.emplace_back(std::string("A"));
temp.emplace_back(10);
temp.emplace_back(3.14f);


So I need to find whether string "A" present in the vector or not. Can std::find help here?



As of now I am using below piece of code to do this



bool isItemPresentInAnyVector(std::vector<std::any> items, std::any item)

for (const auto& it : items)

if (it.type() == typeid(std::string) && item.type() == typeid(std::string))

std::string strVecItem = std::any_cast<std::string>(it);
std::string strItem = std::any_cast<std::string>(item);

if (strVecItem.compare(strItem) == 0)
return true;

else if (it.type() == typeid(int) && item.type() == typeid(int))

int iVecItem = std::any_cast<int>(it);
int iItem = std::any_cast<int>(item);

if (iVecItem == iItem)
return true;

else if (it.type() == typeid(float) && item.type() == typeid(float))

float fVecItem = std::any_cast<float>(it);
float fItem = std::any_cast<float>(item);

if (fVecItem == fItem)
return true;



return false;







c++ c++17 stdany






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 6:59









Eric

67.3k32170283




67.3k32170283










asked Mar 8 at 6:37









ArunArun

82021426




82021426







  • 2





    Read std::find_if.

    – Passer By
    Mar 8 at 6:51






  • 6





    Have you considered using std::variant<int, float, std::string> instead? std::find will work fine on that.

    – Eric
    Mar 8 at 6:57











  • Generic comparisons of std::any would require support from any itself (since you can't any_cast based on type(), which is not known at compile time); For what you seem to be doing, variant is indeed better along multiple dimensions - no extra heap overhead, no hidden virtual dispatch, etc...

    – Stefan Atev
    Mar 8 at 15:58












  • 2





    Read std::find_if.

    – Passer By
    Mar 8 at 6:51






  • 6





    Have you considered using std::variant<int, float, std::string> instead? std::find will work fine on that.

    – Eric
    Mar 8 at 6:57











  • Generic comparisons of std::any would require support from any itself (since you can't any_cast based on type(), which is not known at compile time); For what you seem to be doing, variant is indeed better along multiple dimensions - no extra heap overhead, no hidden virtual dispatch, etc...

    – Stefan Atev
    Mar 8 at 15:58







2




2





Read std::find_if.

– Passer By
Mar 8 at 6:51





Read std::find_if.

– Passer By
Mar 8 at 6:51




6




6





Have you considered using std::variant<int, float, std::string> instead? std::find will work fine on that.

– Eric
Mar 8 at 6:57





Have you considered using std::variant<int, float, std::string> instead? std::find will work fine on that.

– Eric
Mar 8 at 6:57













Generic comparisons of std::any would require support from any itself (since you can't any_cast based on type(), which is not known at compile time); For what you seem to be doing, variant is indeed better along multiple dimensions - no extra heap overhead, no hidden virtual dispatch, etc...

– Stefan Atev
Mar 8 at 15:58





Generic comparisons of std::any would require support from any itself (since you can't any_cast based on type(), which is not known at compile time); For what you seem to be doing, variant is indeed better along multiple dimensions - no extra heap overhead, no hidden virtual dispatch, etc...

– Stefan Atev
Mar 8 at 15:58












4 Answers
4






active

oldest

votes


















4














This should work good I guess:



#include <vector>
#include <string>
#include <any>
#include <algorithm>
#include <iostream>

int main()
std::vector<std::any> temp;
temp.emplace_back(std::string("A"));
temp.emplace_back(10);
temp.emplace_back(3.14f);

int i = 10;//you can use any type for i variable and it should work fine
//std::string i = "A";
auto found = std::find_if(temp.begin(), temp.end(), [i](const auto &a)
return typeid(i) == a.type() && std::any_cast<decltype(i)>(a) == i;
);

std::cout << std::any_cast<decltype(i)>(*found);



Or to make the code a bit more generic and reusable:



#include <vector>
#include <string>
#include <any>
#include <algorithm>
#include <iostream>


auto any_compare = [](const auto &i)
return [i] (const auto &val)
return typeid(i) == val.type() && std::any_cast<decltype(i)>(val) == i;
;
;

int main()
std::vector<std::any> temp;
temp.emplace_back(std::string("A"));
temp.emplace_back(10);
temp.emplace_back(3.14f);

//int i = 10;
std::string i = "A";
auto found = std::find_if(temp.begin(), temp.end(), any_compare(i));

std::cout << std::any_cast<decltype(i)>(*found);



Live demo



Important note: this is guaranteed to work only within single translation unit due to stadard requirements on std::any type (for example same types don't need to have same type identifier in different translation units)






share|improve this answer

























  • Notice that std::find_if(temp.begin(), temp.end(), any_compare(temp[0])) would fail (any of any).

    – Jarod42
    Mar 8 at 9:15











  • @Jarod42 for sake of simplicity I ommited it, but I can fix it

    – bartop
    Mar 8 at 9:17






  • 1





    @bartop: I would say finding an any in a vector of any using equal operator is impossible by design (portably). It can be done implementing std::any differently, but I don't see how you can end up calling equality comparison in a compilation unit that never saw the types wrapped in the any object if the "manager" handling the virtual dispatching doesn't support that operation explicitly (and g++ doesn't because the standard doesn't require it).

    – 6502
    Mar 8 at 11:44












  • @6502 you are right, this will work only with single compilation unit

    – bartop
    Mar 11 at 8:55


















2














Unfortunately if you want to find an std::any instance in a vector of std::any instances the answer is no.



std::any does need some "magic" for example to be able to handle the creation of unknown object types but this machinery is private and must only supports object creation and not equality comparison.



It would be possible to implement what you are looking for using the same approach, but not with standard std::any that doesn't publish the needed details. The "manager" template needs to enumerate all possible operations and, for example, in g++ implementation they're "access", "get_type_info", "clone", "destroy", "xfer".



variant is completely different, because explicitly lists all the allowed types and therefore in any place it's used can access all the methods.






share|improve this answer
































    1














    Using an any for this kind of purpose is not a good use of any. The best way to go is just to use a variant - since you have a closed set of types:



    struct Equals 
    template <typename T>
    constexpr bool operator()(T const& a, T const& b) const return a == b;

    template <typename T, typename U>
    constexpr bool operator()(T const& a, U const& b) const return false;
    ;

    using V = std::variant<int, float, std::string>
    bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)

    auto it = std::find_if(items.begin(), items.end(), [&](V const& elem)
    return std::visit(Equals, elem, item);
    );
    return it != items.end();



    Actually it's even better, because as Kilian points out, variant's operator== already works exactly like this:



    using V = std::variant<int, float, std::string>
    bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)

    return std::find(items.begin(), items.end(), item) != items.end();






    share|improve this answer




















    • 1





      In this case you could even use the variants operator== en.cppreference.com/w/cpp/utility/variant/operator_cmp . auto it = std::find(items.begin(), items.end(), item);

      – Kilian
      Mar 8 at 19:59












    • @Kilian oh lol, :facepalm:

      – Barry
      Mar 8 at 20:24


















    0














    If the types are int, float and string (or a limited set of types), you can use a combination of std::variant and std::get_if to achieve what you want to do in a simple manner:



    std::get_if is to determine which of the types is stored in the std::variant.



    A minimal example:



    #include <iostream>
    #include <vector>
    #include <string>
    #include <variant>

    int main()
    std::vector<std::variant<int, float, std::string>> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);

    for (const auto& var: temp)
    if(std::get_if<std::string>(&var))
    if(std::get<std::string>(var) == "A") std::cout << "found stringn";

    if(std::get_if<int>(&var))
    if(std::get<int>(var) == 10) std::cout << "found intn";

    if(std::get_if<float>(&var))
    if(std::get<float>(var) == 3.14f) std::cout << "found floatn";





    Live Demo






    share|improve this answer




















    • 1





      once you use std::variant, std::visit might help.

      – Jarod42
      Mar 8 at 9:16










    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55057937%2ffind-an-element-in-stdvector-of-stdany%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    4














    This should work good I guess:



    #include <vector>
    #include <string>
    #include <any>
    #include <algorithm>
    #include <iostream>

    int main()
    std::vector<std::any> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);

    int i = 10;//you can use any type for i variable and it should work fine
    //std::string i = "A";
    auto found = std::find_if(temp.begin(), temp.end(), [i](const auto &a)
    return typeid(i) == a.type() && std::any_cast<decltype(i)>(a) == i;
    );

    std::cout << std::any_cast<decltype(i)>(*found);



    Or to make the code a bit more generic and reusable:



    #include <vector>
    #include <string>
    #include <any>
    #include <algorithm>
    #include <iostream>


    auto any_compare = [](const auto &i)
    return [i] (const auto &val)
    return typeid(i) == val.type() && std::any_cast<decltype(i)>(val) == i;
    ;
    ;

    int main()
    std::vector<std::any> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);

    //int i = 10;
    std::string i = "A";
    auto found = std::find_if(temp.begin(), temp.end(), any_compare(i));

    std::cout << std::any_cast<decltype(i)>(*found);



    Live demo



    Important note: this is guaranteed to work only within single translation unit due to stadard requirements on std::any type (for example same types don't need to have same type identifier in different translation units)






    share|improve this answer

























    • Notice that std::find_if(temp.begin(), temp.end(), any_compare(temp[0])) would fail (any of any).

      – Jarod42
      Mar 8 at 9:15











    • @Jarod42 for sake of simplicity I ommited it, but I can fix it

      – bartop
      Mar 8 at 9:17






    • 1





      @bartop: I would say finding an any in a vector of any using equal operator is impossible by design (portably). It can be done implementing std::any differently, but I don't see how you can end up calling equality comparison in a compilation unit that never saw the types wrapped in the any object if the "manager" handling the virtual dispatching doesn't support that operation explicitly (and g++ doesn't because the standard doesn't require it).

      – 6502
      Mar 8 at 11:44












    • @6502 you are right, this will work only with single compilation unit

      – bartop
      Mar 11 at 8:55















    4














    This should work good I guess:



    #include <vector>
    #include <string>
    #include <any>
    #include <algorithm>
    #include <iostream>

    int main()
    std::vector<std::any> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);

    int i = 10;//you can use any type for i variable and it should work fine
    //std::string i = "A";
    auto found = std::find_if(temp.begin(), temp.end(), [i](const auto &a)
    return typeid(i) == a.type() && std::any_cast<decltype(i)>(a) == i;
    );

    std::cout << std::any_cast<decltype(i)>(*found);



    Or to make the code a bit more generic and reusable:



    #include <vector>
    #include <string>
    #include <any>
    #include <algorithm>
    #include <iostream>


    auto any_compare = [](const auto &i)
    return [i] (const auto &val)
    return typeid(i) == val.type() && std::any_cast<decltype(i)>(val) == i;
    ;
    ;

    int main()
    std::vector<std::any> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);

    //int i = 10;
    std::string i = "A";
    auto found = std::find_if(temp.begin(), temp.end(), any_compare(i));

    std::cout << std::any_cast<decltype(i)>(*found);



    Live demo



    Important note: this is guaranteed to work only within single translation unit due to stadard requirements on std::any type (for example same types don't need to have same type identifier in different translation units)






    share|improve this answer

























    • Notice that std::find_if(temp.begin(), temp.end(), any_compare(temp[0])) would fail (any of any).

      – Jarod42
      Mar 8 at 9:15











    • @Jarod42 for sake of simplicity I ommited it, but I can fix it

      – bartop
      Mar 8 at 9:17






    • 1





      @bartop: I would say finding an any in a vector of any using equal operator is impossible by design (portably). It can be done implementing std::any differently, but I don't see how you can end up calling equality comparison in a compilation unit that never saw the types wrapped in the any object if the "manager" handling the virtual dispatching doesn't support that operation explicitly (and g++ doesn't because the standard doesn't require it).

      – 6502
      Mar 8 at 11:44












    • @6502 you are right, this will work only with single compilation unit

      – bartop
      Mar 11 at 8:55













    4












    4








    4







    This should work good I guess:



    #include <vector>
    #include <string>
    #include <any>
    #include <algorithm>
    #include <iostream>

    int main()
    std::vector<std::any> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);

    int i = 10;//you can use any type for i variable and it should work fine
    //std::string i = "A";
    auto found = std::find_if(temp.begin(), temp.end(), [i](const auto &a)
    return typeid(i) == a.type() && std::any_cast<decltype(i)>(a) == i;
    );

    std::cout << std::any_cast<decltype(i)>(*found);



    Or to make the code a bit more generic and reusable:



    #include <vector>
    #include <string>
    #include <any>
    #include <algorithm>
    #include <iostream>


    auto any_compare = [](const auto &i)
    return [i] (const auto &val)
    return typeid(i) == val.type() && std::any_cast<decltype(i)>(val) == i;
    ;
    ;

    int main()
    std::vector<std::any> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);

    //int i = 10;
    std::string i = "A";
    auto found = std::find_if(temp.begin(), temp.end(), any_compare(i));

    std::cout << std::any_cast<decltype(i)>(*found);



    Live demo



    Important note: this is guaranteed to work only within single translation unit due to stadard requirements on std::any type (for example same types don't need to have same type identifier in different translation units)






    share|improve this answer















    This should work good I guess:



    #include <vector>
    #include <string>
    #include <any>
    #include <algorithm>
    #include <iostream>

    int main()
    std::vector<std::any> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);

    int i = 10;//you can use any type for i variable and it should work fine
    //std::string i = "A";
    auto found = std::find_if(temp.begin(), temp.end(), [i](const auto &a)
    return typeid(i) == a.type() && std::any_cast<decltype(i)>(a) == i;
    );

    std::cout << std::any_cast<decltype(i)>(*found);



    Or to make the code a bit more generic and reusable:



    #include <vector>
    #include <string>
    #include <any>
    #include <algorithm>
    #include <iostream>


    auto any_compare = [](const auto &i)
    return [i] (const auto &val)
    return typeid(i) == val.type() && std::any_cast<decltype(i)>(val) == i;
    ;
    ;

    int main()
    std::vector<std::any> temp;
    temp.emplace_back(std::string("A"));
    temp.emplace_back(10);
    temp.emplace_back(3.14f);

    //int i = 10;
    std::string i = "A";
    auto found = std::find_if(temp.begin(), temp.end(), any_compare(i));

    std::cout << std::any_cast<decltype(i)>(*found);



    Live demo



    Important note: this is guaranteed to work only within single translation unit due to stadard requirements on std::any type (for example same types don't need to have same type identifier in different translation units)







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 11 at 8:57

























    answered Mar 8 at 7:41









    bartopbartop

    3,1831030




    3,1831030












    • Notice that std::find_if(temp.begin(), temp.end(), any_compare(temp[0])) would fail (any of any).

      – Jarod42
      Mar 8 at 9:15











    • @Jarod42 for sake of simplicity I ommited it, but I can fix it

      – bartop
      Mar 8 at 9:17






    • 1





      @bartop: I would say finding an any in a vector of any using equal operator is impossible by design (portably). It can be done implementing std::any differently, but I don't see how you can end up calling equality comparison in a compilation unit that never saw the types wrapped in the any object if the "manager" handling the virtual dispatching doesn't support that operation explicitly (and g++ doesn't because the standard doesn't require it).

      – 6502
      Mar 8 at 11:44












    • @6502 you are right, this will work only with single compilation unit

      – bartop
      Mar 11 at 8:55

















    • Notice that std::find_if(temp.begin(), temp.end(), any_compare(temp[0])) would fail (any of any).

      – Jarod42
      Mar 8 at 9:15











    • @Jarod42 for sake of simplicity I ommited it, but I can fix it

      – bartop
      Mar 8 at 9:17






    • 1





      @bartop: I would say finding an any in a vector of any using equal operator is impossible by design (portably). It can be done implementing std::any differently, but I don't see how you can end up calling equality comparison in a compilation unit that never saw the types wrapped in the any object if the "manager" handling the virtual dispatching doesn't support that operation explicitly (and g++ doesn't because the standard doesn't require it).

      – 6502
      Mar 8 at 11:44












    • @6502 you are right, this will work only with single compilation unit

      – bartop
      Mar 11 at 8:55
















    Notice that std::find_if(temp.begin(), temp.end(), any_compare(temp[0])) would fail (any of any).

    – Jarod42
    Mar 8 at 9:15





    Notice that std::find_if(temp.begin(), temp.end(), any_compare(temp[0])) would fail (any of any).

    – Jarod42
    Mar 8 at 9:15













    @Jarod42 for sake of simplicity I ommited it, but I can fix it

    – bartop
    Mar 8 at 9:17





    @Jarod42 for sake of simplicity I ommited it, but I can fix it

    – bartop
    Mar 8 at 9:17




    1




    1





    @bartop: I would say finding an any in a vector of any using equal operator is impossible by design (portably). It can be done implementing std::any differently, but I don't see how you can end up calling equality comparison in a compilation unit that never saw the types wrapped in the any object if the "manager" handling the virtual dispatching doesn't support that operation explicitly (and g++ doesn't because the standard doesn't require it).

    – 6502
    Mar 8 at 11:44






    @bartop: I would say finding an any in a vector of any using equal operator is impossible by design (portably). It can be done implementing std::any differently, but I don't see how you can end up calling equality comparison in a compilation unit that never saw the types wrapped in the any object if the "manager" handling the virtual dispatching doesn't support that operation explicitly (and g++ doesn't because the standard doesn't require it).

    – 6502
    Mar 8 at 11:44














    @6502 you are right, this will work only with single compilation unit

    – bartop
    Mar 11 at 8:55





    @6502 you are right, this will work only with single compilation unit

    – bartop
    Mar 11 at 8:55













    2














    Unfortunately if you want to find an std::any instance in a vector of std::any instances the answer is no.



    std::any does need some "magic" for example to be able to handle the creation of unknown object types but this machinery is private and must only supports object creation and not equality comparison.



    It would be possible to implement what you are looking for using the same approach, but not with standard std::any that doesn't publish the needed details. The "manager" template needs to enumerate all possible operations and, for example, in g++ implementation they're "access", "get_type_info", "clone", "destroy", "xfer".



    variant is completely different, because explicitly lists all the allowed types and therefore in any place it's used can access all the methods.






    share|improve this answer





























      2














      Unfortunately if you want to find an std::any instance in a vector of std::any instances the answer is no.



      std::any does need some "magic" for example to be able to handle the creation of unknown object types but this machinery is private and must only supports object creation and not equality comparison.



      It would be possible to implement what you are looking for using the same approach, but not with standard std::any that doesn't publish the needed details. The "manager" template needs to enumerate all possible operations and, for example, in g++ implementation they're "access", "get_type_info", "clone", "destroy", "xfer".



      variant is completely different, because explicitly lists all the allowed types and therefore in any place it's used can access all the methods.






      share|improve this answer



























        2












        2








        2







        Unfortunately if you want to find an std::any instance in a vector of std::any instances the answer is no.



        std::any does need some "magic" for example to be able to handle the creation of unknown object types but this machinery is private and must only supports object creation and not equality comparison.



        It would be possible to implement what you are looking for using the same approach, but not with standard std::any that doesn't publish the needed details. The "manager" template needs to enumerate all possible operations and, for example, in g++ implementation they're "access", "get_type_info", "clone", "destroy", "xfer".



        variant is completely different, because explicitly lists all the allowed types and therefore in any place it's used can access all the methods.






        share|improve this answer















        Unfortunately if you want to find an std::any instance in a vector of std::any instances the answer is no.



        std::any does need some "magic" for example to be able to handle the creation of unknown object types but this machinery is private and must only supports object creation and not equality comparison.



        It would be possible to implement what you are looking for using the same approach, but not with standard std::any that doesn't publish the needed details. The "manager" template needs to enumerate all possible operations and, for example, in g++ implementation they're "access", "get_type_info", "clone", "destroy", "xfer".



        variant is completely different, because explicitly lists all the allowed types and therefore in any place it's used can access all the methods.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 10 at 20:19

























        answered Mar 8 at 9:16









        65026502

        87.6k13115217




        87.6k13115217





















            1














            Using an any for this kind of purpose is not a good use of any. The best way to go is just to use a variant - since you have a closed set of types:



            struct Equals 
            template <typename T>
            constexpr bool operator()(T const& a, T const& b) const return a == b;

            template <typename T, typename U>
            constexpr bool operator()(T const& a, U const& b) const return false;
            ;

            using V = std::variant<int, float, std::string>
            bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)

            auto it = std::find_if(items.begin(), items.end(), [&](V const& elem)
            return std::visit(Equals, elem, item);
            );
            return it != items.end();



            Actually it's even better, because as Kilian points out, variant's operator== already works exactly like this:



            using V = std::variant<int, float, std::string>
            bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)

            return std::find(items.begin(), items.end(), item) != items.end();






            share|improve this answer




















            • 1





              In this case you could even use the variants operator== en.cppreference.com/w/cpp/utility/variant/operator_cmp . auto it = std::find(items.begin(), items.end(), item);

              – Kilian
              Mar 8 at 19:59












            • @Kilian oh lol, :facepalm:

              – Barry
              Mar 8 at 20:24















            1














            Using an any for this kind of purpose is not a good use of any. The best way to go is just to use a variant - since you have a closed set of types:



            struct Equals 
            template <typename T>
            constexpr bool operator()(T const& a, T const& b) const return a == b;

            template <typename T, typename U>
            constexpr bool operator()(T const& a, U const& b) const return false;
            ;

            using V = std::variant<int, float, std::string>
            bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)

            auto it = std::find_if(items.begin(), items.end(), [&](V const& elem)
            return std::visit(Equals, elem, item);
            );
            return it != items.end();



            Actually it's even better, because as Kilian points out, variant's operator== already works exactly like this:



            using V = std::variant<int, float, std::string>
            bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)

            return std::find(items.begin(), items.end(), item) != items.end();






            share|improve this answer




















            • 1





              In this case you could even use the variants operator== en.cppreference.com/w/cpp/utility/variant/operator_cmp . auto it = std::find(items.begin(), items.end(), item);

              – Kilian
              Mar 8 at 19:59












            • @Kilian oh lol, :facepalm:

              – Barry
              Mar 8 at 20:24













            1












            1








            1







            Using an any for this kind of purpose is not a good use of any. The best way to go is just to use a variant - since you have a closed set of types:



            struct Equals 
            template <typename T>
            constexpr bool operator()(T const& a, T const& b) const return a == b;

            template <typename T, typename U>
            constexpr bool operator()(T const& a, U const& b) const return false;
            ;

            using V = std::variant<int, float, std::string>
            bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)

            auto it = std::find_if(items.begin(), items.end(), [&](V const& elem)
            return std::visit(Equals, elem, item);
            );
            return it != items.end();



            Actually it's even better, because as Kilian points out, variant's operator== already works exactly like this:



            using V = std::variant<int, float, std::string>
            bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)

            return std::find(items.begin(), items.end(), item) != items.end();






            share|improve this answer















            Using an any for this kind of purpose is not a good use of any. The best way to go is just to use a variant - since you have a closed set of types:



            struct Equals 
            template <typename T>
            constexpr bool operator()(T const& a, T const& b) const return a == b;

            template <typename T, typename U>
            constexpr bool operator()(T const& a, U const& b) const return false;
            ;

            using V = std::variant<int, float, std::string>
            bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)

            auto it = std::find_if(items.begin(), items.end(), [&](V const& elem)
            return std::visit(Equals, elem, item);
            );
            return it != items.end();



            Actually it's even better, because as Kilian points out, variant's operator== already works exactly like this:



            using V = std::variant<int, float, std::string>
            bool isItemPresentInAnyVector(std::vector<V> const& items, V const& item)

            return std::find(items.begin(), items.end(), item) != items.end();







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 8 at 20:25

























            answered Mar 8 at 16:18









            BarryBarry

            185k21326601




            185k21326601







            • 1





              In this case you could even use the variants operator== en.cppreference.com/w/cpp/utility/variant/operator_cmp . auto it = std::find(items.begin(), items.end(), item);

              – Kilian
              Mar 8 at 19:59












            • @Kilian oh lol, :facepalm:

              – Barry
              Mar 8 at 20:24












            • 1





              In this case you could even use the variants operator== en.cppreference.com/w/cpp/utility/variant/operator_cmp . auto it = std::find(items.begin(), items.end(), item);

              – Kilian
              Mar 8 at 19:59












            • @Kilian oh lol, :facepalm:

              – Barry
              Mar 8 at 20:24







            1




            1





            In this case you could even use the variants operator== en.cppreference.com/w/cpp/utility/variant/operator_cmp . auto it = std::find(items.begin(), items.end(), item);

            – Kilian
            Mar 8 at 19:59






            In this case you could even use the variants operator== en.cppreference.com/w/cpp/utility/variant/operator_cmp . auto it = std::find(items.begin(), items.end(), item);

            – Kilian
            Mar 8 at 19:59














            @Kilian oh lol, :facepalm:

            – Barry
            Mar 8 at 20:24





            @Kilian oh lol, :facepalm:

            – Barry
            Mar 8 at 20:24











            0














            If the types are int, float and string (or a limited set of types), you can use a combination of std::variant and std::get_if to achieve what you want to do in a simple manner:



            std::get_if is to determine which of the types is stored in the std::variant.



            A minimal example:



            #include <iostream>
            #include <vector>
            #include <string>
            #include <variant>

            int main()
            std::vector<std::variant<int, float, std::string>> temp;
            temp.emplace_back(std::string("A"));
            temp.emplace_back(10);
            temp.emplace_back(3.14f);

            for (const auto& var: temp)
            if(std::get_if<std::string>(&var))
            if(std::get<std::string>(var) == "A") std::cout << "found stringn";

            if(std::get_if<int>(&var))
            if(std::get<int>(var) == 10) std::cout << "found intn";

            if(std::get_if<float>(&var))
            if(std::get<float>(var) == 3.14f) std::cout << "found floatn";





            Live Demo






            share|improve this answer




















            • 1





              once you use std::variant, std::visit might help.

              – Jarod42
              Mar 8 at 9:16















            0














            If the types are int, float and string (or a limited set of types), you can use a combination of std::variant and std::get_if to achieve what you want to do in a simple manner:



            std::get_if is to determine which of the types is stored in the std::variant.



            A minimal example:



            #include <iostream>
            #include <vector>
            #include <string>
            #include <variant>

            int main()
            std::vector<std::variant<int, float, std::string>> temp;
            temp.emplace_back(std::string("A"));
            temp.emplace_back(10);
            temp.emplace_back(3.14f);

            for (const auto& var: temp)
            if(std::get_if<std::string>(&var))
            if(std::get<std::string>(var) == "A") std::cout << "found stringn";

            if(std::get_if<int>(&var))
            if(std::get<int>(var) == 10) std::cout << "found intn";

            if(std::get_if<float>(&var))
            if(std::get<float>(var) == 3.14f) std::cout << "found floatn";





            Live Demo






            share|improve this answer




















            • 1





              once you use std::variant, std::visit might help.

              – Jarod42
              Mar 8 at 9:16













            0












            0








            0







            If the types are int, float and string (or a limited set of types), you can use a combination of std::variant and std::get_if to achieve what you want to do in a simple manner:



            std::get_if is to determine which of the types is stored in the std::variant.



            A minimal example:



            #include <iostream>
            #include <vector>
            #include <string>
            #include <variant>

            int main()
            std::vector<std::variant<int, float, std::string>> temp;
            temp.emplace_back(std::string("A"));
            temp.emplace_back(10);
            temp.emplace_back(3.14f);

            for (const auto& var: temp)
            if(std::get_if<std::string>(&var))
            if(std::get<std::string>(var) == "A") std::cout << "found stringn";

            if(std::get_if<int>(&var))
            if(std::get<int>(var) == 10) std::cout << "found intn";

            if(std::get_if<float>(&var))
            if(std::get<float>(var) == 3.14f) std::cout << "found floatn";





            Live Demo






            share|improve this answer















            If the types are int, float and string (or a limited set of types), you can use a combination of std::variant and std::get_if to achieve what you want to do in a simple manner:



            std::get_if is to determine which of the types is stored in the std::variant.



            A minimal example:



            #include <iostream>
            #include <vector>
            #include <string>
            #include <variant>

            int main()
            std::vector<std::variant<int, float, std::string>> temp;
            temp.emplace_back(std::string("A"));
            temp.emplace_back(10);
            temp.emplace_back(3.14f);

            for (const auto& var: temp)
            if(std::get_if<std::string>(&var))
            if(std::get<std::string>(var) == "A") std::cout << "found stringn";

            if(std::get_if<int>(&var))
            if(std::get<int>(var) == 10) std::cout << "found intn";

            if(std::get_if<float>(&var))
            if(std::get<float>(var) == 3.14f) std::cout << "found floatn";





            Live Demo







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 8 at 8:04

























            answered Mar 8 at 7:52









            P.WP.W

            17.1k41555




            17.1k41555







            • 1





              once you use std::variant, std::visit might help.

              – Jarod42
              Mar 8 at 9:16












            • 1





              once you use std::variant, std::visit might help.

              – Jarod42
              Mar 8 at 9:16







            1




            1





            once you use std::variant, std::visit might help.

            – Jarod42
            Mar 8 at 9:16





            once you use std::variant, std::visit might help.

            – Jarod42
            Mar 8 at 9:16

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55057937%2ffind-an-element-in-stdvector-of-stdany%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme