在c ++中增加字符串数组的大小

时间:2017-12-15 16:58:07

标签: c++ arrays string

我想在声明一次之后增加字符串数组的大小,怎么做呢。我需要在以下代码中增加大小..

#include<iostream>
using namespace std;
#include<string>
int main()
{
    int n;
    string A[] =
    { "vaibhav", "vinayak", "alok", "aman" };
    int a = sizeof(A) / sizeof(A[0]);
    cout << "The size is " << a << endl;
    for (int i = 0; i < a; i++)
    {
        cout << A[i] << endl;
    }
    cout << "Enter the number of elements you want to add to the string"
            << endl;
    cin >> n;
    cout << "ok now enter the strings" << endl;
    for (int i = a; i < n + a; i++)
    {
        cin >> A[i];
    }
    a = a + n;
    A.resize(a); // THIS KIND OF THING
    for (int i = 0; i < a; i++)
    {
        cout << A[i] << endl;
    }
    return 0;
}

4 个答案:

答案 0 :(得分:3)

简单明了:你做不到。

你可以获得一个更大的数组,复制你所有的东西,然后使用它。但为什么要这样做,当有一个非常好的课程时,为你做这一切:std::vector

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::vector<std::string> A = {"vaibhav", "vinayak", "alok", "aman"};

    std::cout << "The size is " << A.size() << std::endl;

    for(string s : A) 
    {
        std::cout << s << std::endl;
    }

    // want to enter more?
    sd::string more;
    std::cin >> more;
    A.push_back(more);

    std::cout << "The size is " << A.size() << std::endl;
    for(string s : A)
    {
        std::cout << s << std::endl;
    }

    return 0;
}

答案 1 :(得分:2)

将代码转换为使用std::vector,这个问题变得更容易解决。

#include<iostream>
#include<string>
#include<vector>

int main(){
    int n;
    std::vector<std::string> A = {"vaibhav", "vinayak", "alok", "aman"};
    int a = A.size();
    std::cout << "The size is " << a << std::endl;
    //Prefer Range-For when just iterating over all elements
    for(std::string const& str : A){
        std::cout << str << std::endl;
    }
    std::cout << "Enter the number of elements you want to add to the string" << std::endl;
    std::cin >> n;
    std::cout << "ok now enter the strings" << std::endl;
    for(int i = 0; i < n; i++ ) {
        //emplace_back automatically resizes the container when called.
        A.emplace_back();
        std::cin >> A.back();
        //If you're using C++17, you can replace those two lines with just this:
        //std::cin >> A.emplace_back();
    }
    for(std::string const& str : A){
        std::cout << str << std::endl;
    }
    return 0;
}

另外,don't use using namespace std;,因为它会导致修复错误并使你的代码更难以阅读其他C ++程序员。

答案 2 :(得分:1)

  

我想在声明之后增加字符串数组的大小   曾经,怎么办呢。

无法做到。如果元素计数在编译时未知或可以动态更改,请使用std::vector。它甚至有一个resize成员函数,其名称与代码中的成员函数完全相同。

答案 3 :(得分:0)

您不能增加原始数组的大小,您可以使用std::vecto<std::string>,因为这种类型的数组可以在运行时增长。

但是,您还可以创建一个类,该类将存储一个字符串数组并创建您自己的实现来调整原始数组的大小。这将创建一个更大的数组并复制所有其他值,然后将类数组设置为新数组(或只是返回它)