How to Create a Vector of Character Arrays in C++

The C++ programming language has a library of generic containers known as the Standard Template Library or STL. One useful container from the STL is the vector. A vector is a container of sequential data, which makes it similar to an array. Unlike an array, a vector can change size as its contents are modified. You can create vectors of many different data types with the exception of arrays. You can create vectors to pointers to character arrays. Since the identifier to an array is a pointer, this accomplishes a similar result as storing arrays in vectors.

Things You'll Need

  • C++ Integrated Development Environment or IDE, such as Eclipse CDT
  • C++ Compiler, such a GCC
Show More

Instructions

    • 1

      Load the C++ IDE by clicking on its program icon. When it opens, select "File/New/Project" and choose "C ++Project" to create a new C++ project. A blank source code file appears in the text editor portion of the IDE.

    • 2

      Import the vector library by writing the following statement at the top of the source code:

      #include <vector>

    • 3

      Use the std namespace. By writing the following statement, you will not have to append the word "std" to every vector function:

      using namespace std;

    • 4

      Create a main function by writing the following line of code:

      int main() {}

    • 5

      Declare several character arrays by writing the following statements inside the curly brackets of the main function:

      char a[5] = 'abcde';

    • 6

      Create a new vector that stores pointers to characters. The identifier to an array is a pointer, which can be stored in vectors. To declare a vector to char pointers, write the following:

      vector<char*> v;

    • 7

      Push the char array into the vector using the push_back function, like this:

      v.push_back(a);

    • 8

      Execute the program by pressing the green play button located in the top row of buttons on the IDE. The program will create an array, a vector of char pointers, and push the array pointer into the vector.

Related Searches:

References

Comments

You May Also Like

  • How to Print Pointers in C

    Pointers provide programmers with the ability to alias a variable by "pointing" to its address space. A pointer is assigned a variable's...

  • How to Initialize Variables in C

    C does not initialize variables automatically, so if you do not initialize them properly, you can get unexpected results. Fortunately, C makes...

  • How to Create an Array in C

    Arrays offer the most efficient method for storing lists of data in C. They're very easy for the programmer to create and...

  • How to Use C Arrays in C++

    A C array is a data structure that stores many elements of the same data type. C arrays, when you use them...

Related Ads

Featured