Thread: "Implode" an Array

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    27

    "Implode" an Array

    Does C++ have a function similar to the PHP function, implode?

    For example:

    Code:
    $var = implode('|',$thearray);
    Which would join the array values together in a string with the | character in this case, eg: item1|item2|item2|etc

    I know you can use a for loop in C++ to loop through each item (or write a custom function) but i was wondering if there is an implode style function in existence.

    As a side note, does c++ support associative arrays? eg: array["key"], array["anotherkey"] etc. Judging by what i have seen so far it seems that numeric keys are the only option, i'd just like to confirm this.

    Thank you very much

  2. #2
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Quote Originally Posted by Diablo84
    As a side note, does c++ support associative arrays? eg: array["key"], array["anotherkey"] etc.
    Yes, in C++ they're called maps.

    Code:
    #include <map>
    #include <string>
    using std::map,std::string;
    ...
    
    map<string, int> array;
    array["one"] = 1;
    array["two"] = 2;

    EDIT:
    And there's no 'implode' function, but it's easy to write one:

    Code:
    #include <sstream>
    #include <string>
    template <typename T>
    std::string implode(char ch, std::vector<T> vec)
    {
      std::stringstream out;
      for (int p=0;p<vec.length()-1;++p)
        out << vec[p] << ch;
      out << vec[vec.length()-1];
      return out.str();
    }
    Last edited by Sang-drax; 04-10-2005 at 11:27 AM.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  3. #3
    Registered User
    Join Date
    Aug 2004
    Location
    San Diego, CA
    Posts
    313
    Quote Originally Posted by Diablo84
    As a side note, does c++ support associative arrays? eg: array["key"], array["anotherkey"] etc. Judging by what i have seen so far it seems that numeric keys are the only option, i'd just like to confirm this.

    Thank you very much
    std::map will do exactly what you're looking for.

  4. #4
    Registered User
    Join Date
    Mar 2005
    Posts
    27
    Thank you, i hadn't expected associative arrays... or maps, to be available so that's an added bonus.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. from 2D array to 1D array
    By cfdprogrammer in forum C Programming
    Replies: 17
    Last Post: 03-24-2009, 10:33 AM
  3. Replies: 6
    Last Post: 11-09-2006, 03:28 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM