简体   繁体   中英

How do I store strings (or any type) into an array of type T?

I'm trying to store a string (or any type) inside an array of type T, but I get two errors:

a reference of type "std::string &" (not const-qualified) cannot be initialized with a value of type "const char [3]"

'bool container::insertBack(T &)': cannot convert argument 1 from 'const char [3]' to 'T &'

I've tried changing the type to int instead of string: I received similar error messages.

#include <iostream>
#include <string>

template<typename T>
class container
{
public:
    container();
    // Postcondition: data member n is initialized to -1 and all elements in the empty arr array are initialized to zero
    bool isFull();
    // Postcondition: returns true if the container object (i.e., the arr array) is full; returns false otherwise
    bool insertBack(T& val);
    //  Precondition: the container object is not full
    // Postcondition: if arr array is not full, n is incremented by 1; returns true with val is inserted at the end of the arr array 
    //                 Otherwise, returns false; the value is not inserted and program execution continues.
private:
    static const int CAPACITY = 10;     // physical size of the arr array or the storage capacity of a container object
    T arr[CAPACITY];            // arr array can store up to CAPACITY  (10 in our case) of any type 
    int n;                      // n is used as the subscript for the arr array. n is initialized to -1 for an empty array
                                // Each time a new value is inserted into the arr array, n must first be incremented 
                                // by 1. Since n has been initialized to -1, the first inserted value is stored in arr[0],
                                // and the 2nd inserted value will be in arr[1], etc.  and the nth inserted value will be 
                                // stored in arr[n – 1]. Obviously, n + 1 represents the actual number of elements
                                // stored in the array after n rounds of insertion.         
};

template<typename T>
container<T>::container()
{
    n = -1;
    T arr[CAPACITY] = { 0 };
}

template<typename T>
bool container<T>::isFull()
{
    return n == CAPACITY - 1;
}

template<typename T>
bool container<T>::insertBack(T& val)
{
    if (!isFull())
    {
        n++;
        arr[n - 1] = val;
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    container<std::string> s1;
    s1.insertBack("aa");
}

g++ gives a slightly different output for the same error:

cannot bind non-const lvalue reference of type 'std::__cxx11::basic_string<char>&' to an rvalue of type 'std::__cxx11::basic_string<char>'

clang++ :

non-const lvalue reference to type 'std::__cxx11::basic_string<char>' cannot bind to a value of unrelated type 'const char [3]'

The solution is to take the argument as a const& .

What you'll find next is that T arr[CAPACITY] = { 0 };
gives a runtime exception like: basic_string::_M_construct null not valid .

You are not zero initializing arr like that. In fact, you are creating a new arr and trying to construct it with nullptr , which will not work for std::string[] .

You might as well use an unsigned integer as size_t for counting elements as the standard containers do to make future interactions with standard functions/algorithms easier.

With that fixed::

#include <iostream>
#include <string>

template<typename T, size_t Capacity = 10>       // made the capacity selectable
class container {
public:
    container() : arr{}, n(0) {}                 // using member initializer list

    bool isFull() const { return n == Capacity; } // correct test with a 0 based counter

    bool insertBack(const T& val) {               // const
        if (isFull()) return false;
        // return true or false, not 1 or 0 
        arr[n++] = val;
        return true;
    }

private:
    T arr[Capacity];
    size_t n;
};

int main() {
    container<std::string> s1;
    s1.insertBack("aa");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM