Re: finding an index in an STL vector<>
From: David Hilsee (davidhilseenews_at_yahoo.com)
Date: 08/31/04
- Next message: victor goban: "How to expand my compiler's ULONG_MAX ?"
- Previous message: Scott Simontis: "Re: Tutorial for beginner/ Tutorial voor beginner"
- In reply to: Joe: "finding an index in an STL vector<>"
- Next in thread: Joe Harris: "Re: finding an index in an STL vector<>"
- Reply: Joe Harris: "Re: finding an index in an STL vector<>"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 30 Aug 2004 20:58:05 -0400
"Joe" <joe.harris@gmail.com> wrote in message
news:60492282.0408301647.39e55e5d@posting.google.com...
> I have a: vector<string> which contains a few dozen elements.
>
> I want to find the index of the element containing a certain string.
>
> for example:
>
> vector<string> strings;
> strings.push_back("abc");
> strings.push_back("xyz");
> strings.push_back("lmnop");
>
> int index = distance(strings.begin(), find(strings.begin(),
> strings.end(), string("xyz")));
>
> cout << index << endl; // should print out a '1', the index of "xyz"
>
> The above line using 'distance' seems pretty terrible to me. Please
> tell me that there a better way?
Ah, it's not that bad. The explicit construction of the std::string can be
eliminated to make it a little prettier, right? I can't think of anything
better offhand. If you think it's ugly, wrap it.
// optionally a template
std::size_t index_of_element( std::vector<std::string&>& vec, const
std::string& elem );
int index = index_of_element( strings, "xyz" );
But why do you want the index when you already have an iterator?
-- David Hilsee
- Next message: victor goban: "How to expand my compiler's ULONG_MAX ?"
- Previous message: Scott Simontis: "Re: Tutorial for beginner/ Tutorial voor beginner"
- In reply to: Joe: "finding an index in an STL vector<>"
- Next in thread: Joe Harris: "Re: finding an index in an STL vector<>"
- Reply: Joe Harris: "Re: finding an index in an STL vector<>"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|