By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,898 Members | 2,012 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,898 IT Pros & Developers. It's quick & easy.

Need help with STL

P: n/a
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.
Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
"Tom" <sn***@hotmail.com> wrote in message
news:78**************************@posting.google.c om...
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

Jul 22 '05 #2

P: n/a
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

"Tom" <sn***@hotmail.com> wrote in message
news:78**************************@posting.google.c om...
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.

Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.