question in array

question can how can i add new elements in an array that already has existing elements?? im adding strings to the array btw
Last edited on
You can't.

If you have an array of size X, and you want to add a new element to it so that now the array is size X+1, you can't.

You have to create a new array of size X+1, and copy things over.

This being C++ and you being a beginnner, don't use arrays. Don't use arrays. Don't use arrays. Don't use arrays. Don't use arrays.

You're looking for a vector<string>, and the vector insert function ( http://www.cplusplus.com/reference/vector/vector/insert/ )
Last edited on
Add to end of vector http://www.cplusplus.com/reference/vector/vector/emplace_back/
That is more efficient than inserting into the middle.
but for example i have an array size of 15 and i put 5 values set in. then i need to add more via user input how do i do that?
Last edited on
You can use a for loop for that and a count variable to keep track of where you're at. You'd probably be more interested in vectors, however.
cause i need to make a program that has 5 default driver license and i need to add more but i dont know how would i do it
You can set elements of an array at any time.

1
2
array[5] = someNewValue; // set the 6th element of the array
array[6] = someOtherValue; // set the 7th element of the array 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
constexpr size_t Capacity = 15;
size_t size = 0;

std::string words [Capacity];

// put 5 values:
std::string input;
while ( size < 5 and size < Capacity and std::cin >> input ) {
  words[ size++ ] = input;
}

// add another word
if ( size < Capacity ) {
  words[ size++ ] = "hello";
}

// show words
for ( size_t w=0; w < size; ++w ) {
  std::cout << words[ w ] << '\n';
}

Technically we do not add any strings; the array has 15 strings all the time. We simply update some strings and care only about the size first strings.

Vectors are more convenient:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::vector<std::string> words;
words.reserve(15); // optional
// words is still empty. 0 strings in it.

// put 5 values:
std::string input;
while ( words.size() < 5 and std::cin >> input ) {
  words.emplace_back( input );
}

// add another word
words.emplace_back( "hello" );

// show words
for ( auto w : words ) {
  std::cout << w << '\n';
}
Topic archived. No new replies allowed.