En C++ compruebe si std:: vector contiene un cierto valor [duplicar]


Esta pregunta ya tiene una respuesta aquí:

¿Hay alguna función incorporada que me diga que mi vector contiene un cierto elemento o no por ejemplo,

std::vector<string> v;
v.push_back("abc");
v.push_back("xyz");

if (v.contains("abc")) // I am looking for one such feature, is there any
                       // such function or i need to loop through whole vector?
Author: jogojapan, 2011-06-08

5 answers

Puede utilizar std::find como sigue:

if (std::find(v.begin(), v.end(), "abc") != v.end())
{
  // Element in vector.
}

Para poder utilizar std::find: include <algorithm>.

 132
Author: Darhuuk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-28 18:47:01
  1. Si su contenedor solo contiene valores únicos, considere usar std::set en su lugar. Permite consultar la pertenencia a un conjunto con complejidad logarítmica.

    std::set<std::string> s;
    s.insert("abc");
    s.insert("xyz");
    if (s.find("abc") != s.end()) { ...
    
  2. Si su vector se mantiene ordenado, utilice std::binary_search, también ofrece complejidad logarítmica.

  3. Si todo lo demás falla, vuelva a std::find, que es una simple búsqueda lineal.

 24
Author: Alex B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-08 11:00:54

En C++11, puede usar std::any_of en su lugar.

 11
Author: colddie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-08 10:27:42

Está en <algorithm> y se llama std::find.

 4
Author: Nim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-08 10:58:48
 3
Author: Oliver Charlesworth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-08 10:59:01