I want to ask you how it should look like this code for C ++

I want to ask you how this code should look in C ++:

<?php
for ($i = 1; $i <= 10; $i++) {
    $array[$i]="test".$i;
}
?>
+3
source share
3 answers

It will look something like this (full program).

/* required headers */
#include <map>
#include <cstdlib>

/* code has to be inside a function; main is the start-point of the program */
int main() {
  std::map<int, int> array;
  for (int i = 1; i <= 10; ++i) {
    array[i] = i;
  }
  return EXIT_SUCCESS;
}

I use the map above, since the PHP β€œarrays” are actually similar to maps in other languages ​​(although completely mimicking their behavior in a statically typed language is a problem). Of course, since the program does little, you can save yourself spelling and not type in something that does nothing effectively.

EDIT:

/* required headers */
#include <map>
#include <string>
#include <sstream>
#include <cstdlib>

/* code has to be inside a function; main is the start-point of the program */
int main() {
  std::map<int, std::string> array;
  for (int i = 1; i <= 10; ++i) {
    std::ostringstream stream;
    stream << "test" << i;
    array[i] = stream.str();
  }
  return EXIT_SUCCESS;
}
+6
source

Change based on your changes

An important addition to other answers that php does not require:

#include <sstream>
#include <string>

int main
{
   using namespace std;
   string array[11]; // tell the compiler array is an array of size 11
                     // this array starts at index 0 and goes up to 10
                     // totaling 11 elements
   for ( int i=1; i<=10; i++){  // you might want to start at 0 here
      ostringstream strStream
      strStream << "test" << i;
      array[i] = strStream.str();
   }
   return 0;
}

// accessing array outside the bounds you told the compiler
// results in undefined behavior, practically this means crash
// or data corruption

. , , std:: map @eq-answer , , . C .

+3
for ( int i=1; i<=10; i++){
   array[i] = i;
}
-1
source

Source: https://habr.com/ru/post/1788688/


All Articles