动态数组,如果条件满足以供以后使用

时间:2016-04-27 00:34:44

标签: c++ arrays

我是初学者,所以这是初学者的问题。 C ++

如果用户选择== 1,我希望程序创建一个大小的动态数组供用户决定。该数组稍后将用于进一步的操作。如果选择不是== 1,则不要创建任何内容。

我尝试了什么:

int main()
{

std::cin>>choice;

if (choice==1) 
{
int * size = new int;
std::cin >> *size ;
double *array = new double[*size];
}

return 0;
}

但是,如果我这样说,数组不存在于“if”之外。 如果用户选择== 1但是仅在这种情况下,我如何获得为进一步使用而创建的动态数组? 我已经没想完了。

4 个答案:

答案 0 :(得分:1)

#include <iostream>
#include <vector>
using namespace std;

auto main()
    -> int
{
    int choice;
    cin >> choice;

    vector<int> array;
    if( choice == 1 )
    {
        int size;
        cin >> size;
        array.resize( size );
    }

    // Here you can use array
}

免责声明:编码器未检查代码。

答案 1 :(得分:0)

将数组放在if语句的范围之外:

int main()
{
    int choice;
    std::cin>>choice;
    double *array;

    if (choice==1) 
    {
       int * size = new int;
       std::cin >> *size ;
       array = new double[*size];
    }

    return 0;
}

但是,由于您使用的是C ++,请考虑改为使用vector

答案 2 :(得分:0)

将变量声明移到块外,以修复原始问题。

int main()
{
    double *array = null;

    std::cin>>choice;

    if (choice==1) 
    {
        int * size = new int;
        std::cin >> *size ;
        array = new double[*size];
    }

    // at this point array is ether null or a pointer to a buffer

    return 0;
}

或者,更多改进

int main()
{
    double *array = null;
    int choice;

    std::cin>>choice;

    if (choice==1) 
    {
        std::cin >> choice ;
        array = new double[choice];
    }

    // at this point array is ether == null or a pointer to a buffer

    delete[] array;   <--- don't forget to delete it!
    return 0;
}

答案 3 :(得分:0)

我宁愿推荐使用std :: vector:它可以轻松调整大小 此外,您不需要为指针分配内存

<?php
    require __DIR__ . '/vendor/autoload.php';

    define('APPLICATION_NAME', 'Directory API PHP Quickstart');
    define('CREDENTIALS_PATH', '~/.credentials/admin-directory_v1-php-quickstart.json');
    define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret1.json');
    // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/admin-directory_v1-php-quickstart.json
    define('SCOPES', implode(' ', array(
      //Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
      Google_Service_Directory::ADMIN_DIRECTORY_USER)
    ));

    if (php_sapi_name() != 'cli') {
      throw new Exception('This application must be run on the command line.');
    }

    /**
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
     */
    function getClient() {
      $client = new Google_Client();
      $client->setApplicationName(APPLICATION_NAME);
      $client->setScopes(SCOPES);
      $client->setAuthConfigFile(CLIENT_SECRET_PATH);
      $client->setAccessType('offline');

      // Load previously authorized credentials from a file.
      $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
      if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
      } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));

        // Exchange authorization code for an access token.
        $accessToken = $client->authenticate($authCode);

        // Store the credentials to disk.
        if(!file_exists(dirname($credentialsPath))) {
          mkdir(dirname($credentialsPath), 777, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
      }
      $client->setAccessToken($accessToken);

      // Refresh the token if it's expired.
      if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
      }
      return $client;
    }

    /**
     * Expands the home directory alias '~' to the full path.
     * @param string $path the path to expand.
     * @return string the expanded path.
     */
    function expandHomeDirectory($path) {
      $homeDirectory = getenv('HOME');
      if (empty($homeDirectory)) {
        $homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
      }
      return str_replace('~', realpath($homeDirectory), $path);
    }

    // Get the API client and construct the service object.
    $client = getClient();
    $service = new Google_Service_Directory($client);

    //enviar creacion de usuario
    $user = new Google_Service_Directory_User();
    $name = new Google_Service_Directory_UserName();
    // SET THE ATTRIBUTES
    $name->setGivenName('pruebanueve');
    $name->setFamilyName('Testerton');
    $user->setName($name);
    $user->setHashFunction("MD5");
    $user->setPrimaryEmail("prueba@dom.com");
    $user->setPassword(hash("md5","holamundo"));


    try 
    { 
        $createUserResult = $service -> users -> insert($user); 
        var_dump($createUserResult); 
    } 
    catch (Google_IO_Exception $gioe) 
    { 
        echo "Error in connection: ".$gioe->getMessage(); 
    } 
    catch (Google_Service_Exception $gse) 
    { 
        echo $gse->getMessage(); 
    } 

    //print $results;


    // Print the first 10 users in the domain.
    /*$optParams = array(
      'customer' => 'my_customer',
      'maxResults' => 10,
      'orderBy' => 'email',
    );
    $results = $service->users->listUsers($optParams);

    if (count($results->getUsers()) == 0) {
      print "No users found.\n";
    } else {
      print "Users:\n";
      foreach ($results->getUsers() as $user) {
        printf("%s (%s) (%s) \n", $user->getPrimaryEmail(),
            $user->getName()->getFullName(),
            $user->getlastLoginTime());
      }
    }*/
    ?>

http://www.cplusplus.com/reference/vector/vector/resize/

使用C ++时,您应该使用诸如向量而不是数组之类的容器。 C ++容器带有许多非常有用的功能(调整大小只是其中之一)。

http://www.cplusplus.com/reference/stl/

我还强烈建议在使用之前检查尺寸值,因为最终可能会出现意外结果。

示例:

int main() {
    int * size;
    std::cin>>choice;
    std::vector<double> myvector;
    if (choice==1) 
    {
        std::cin >> *size ;
        myvector.resize(*size);
    }
    return 0;
}