Re: finding an index in an STL vector<>

From: David Hilsee (davidhilseenews_at_yahoo.com)
Date: 08/31/04


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


Relevant Pages

  • Re: searching what groups a user belong from AD but errorThe Kerberos subsystem encountered an error
    ... I was just about to write back Joe. ... private string BuildFilterOctetString ... Co-author of "The .NET Developer's Guide to Directory Services ... DirectoryEntry searchRoot = new DirectoryEntry( ...
    (microsoft.public.dotnet.framework.aspnet.security)
  • Re: LogonUser access denied
    ... Joe - really appreciate your efforts on this one, i will try the privilege ... private static extern int LogonUser(String lpszUsername, ...
    (microsoft.public.dotnet.framework.aspnet.security)
  • Re: 32-bit programs on Windows x64
    ... tiny individual sequences. ... to compare its input string against every possible ... compare one string against one string, ...
    (microsoft.public.vc.mfc)
  • Re: 32-bit programs on Windows x64
    ... machine has "parallelism" ... to compare its input string against every possible valid ...
    (microsoft.public.vc.mfc)
  • Re: passing a string to a dll
    ... I might handle the array. ... I actually have been wondering if I could use a second string ... look at insertion cost, organization cost, and search cost. ...
    (microsoft.public.vc.mfc)