Thread: search array?

  1. #1
    Registered User
    Join Date
    Aug 2002
    Posts
    24

    Question search array?

    hey guys,

    Do you know how to search the array for the word (string type) and if the word does not exist in the array, add it to the array?
    I did something like this (see code below), but I fear that for every value in the arraythat is not equal to the word, the same word will be added as many times as the total numbers of values in the array. I need to add only ONE value if none of other values in the array are the same as the value I want to add to array.

    Wrong code:
    Code:
    #include"lvp/vector.h"
    #include<string.h>
    ...
    vector<string>col2;
    for(int k=0; k<col2.length(); k++)
    {
          if(col2[k]!=word)
          {
                 col2.resize(col2.length()+1);
                 col2[b]=word;
                 b++;
          }
    }
    Your input will be greatly appreciated!

    thanks,
    Dmitry Kashlev

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Something like
    Code:
    bool found = false;
    for(int k=0; k<col2.length() && !found; k++)
    {
      // this loop quits when
      // - the word has been found
      // - all the words have been searched
      if ( col2[k] == word ) found = true;
    }
    
    // did we find it
    if ( !found )
    {
      int pos = col2.length();
      col2.resize(pos+1);
      col2[pos]=word;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  2. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM
  3. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  4. search array program
    By z.tron in forum C++ Programming
    Replies: 3
    Last Post: 11-15-2002, 07:33 AM
  5. binary search in an array
    By brianptodd in forum C++ Programming
    Replies: 4
    Last Post: 11-12-2002, 02:05 PM