Need help with STL

T

Tom

I have a vector with alot of elements that contain a string like the
first element would be 123x and another would be 456o and on and on, I
would like to search for one of these but don't know how to search for
it in the vector, can anyone give me an example or help me? I would
very much appreciate it.
 
M

Mike Wahler

Tom said:
I have a vector with alot of elements that contain a string like the
first element would be 123x and another would be 456o and on and on, I
would like to search for one of these but don't know how to search for
it in the vector, can anyone give me an example or help me? I would
very much appreciate it.

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

int main()
{
std::vector<std::string> vec;
vec.push_back("123x");
vec.push_back("456o");
vec.push_back("789z");

std::string to_find("456o");

std::vector<std::string>::const_iterator it
(std::find(vec.begin(), vec.end(), to_find));

std::cout << "The string '" << to_find << "'";

if(it != vec.end())
std::cout <<" found at vector element " << it - vec.begin();
else
std::cout << " not found";

std::cout << '\n';

return 0;
}


-Mike
 
C

Christine

Any particular reason you are using a vector for this? An STL set would be
better suited to the job of quick, associational lookup. Or consider a map
if you want to associate these string "keys" with some other data.

Christine
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top