简体   繁体   English

如何将字符串(或任何类型)存储到 T 类型的数组中?

[英]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:我试图在 T 类型的数组中存储一个字符串(或任何类型),但出现两个错误:

a reference of type "std::string &" (not const-qualified) cannot be initialized with a value of type "const char [3]" “std::string &”类型的引用(非const限定)不能用“const char [3]”类型的值初始化

'bool container::insertBack(T &)': cannot convert argument 1 from 'const char [3]' to 'T &' “bool container::insertBack(T &)”:无法将参数 1 从“const char [3]”转换为“T &”

I've tried changing the type to int instead of string: I received similar error messages.我尝试将类型更改为 int 而不是 string:我收到了类似的错误消息。

#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:对于相同的错误, g++给出了略有不同的输出:

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

clang++ : 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& .解决方案是将参数作为const&

What you'll find next is that T arr[CAPACITY] = { 0 };接下来你会发现T arr[CAPACITY] = { 0 };
gives a runtime exception like: basic_string::_M_construct null not valid .给出一个运行时异常,如: basic_string::_M_construct null not valid

You are not zero initializing arr like that.你不是零初始化arr那样。 In fact, you are creating a new arr and trying to construct it with nullptr , which will not work for std::string[] .事实上,您正在创建一个新的arr并尝试使用nullptr构造它,这不适用于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.您也可以像标准容器一样使用无符号整数作为size_t来计算元素,以便将来与标准函数/算法的交互更容易。

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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将字符串添加到我的 struct 类型数组中,该数组同时包含 C++ 中的字符串和整数? - How do I add a string to my array of type struct which contains both strings and ints in c++? 如何在 C++ 中动态存储和访问类型? - How do I store and access a type dynamically in c++? 如何制作一个可以容纳任何类型指针的容器 - How do I make a container that holds pointers of any type 当我使用自定义类型创建动态数组时,即使使用字符串,它似乎也不起作用 - When I create a dynamic array with a custom type, even with strings, it doesn't seem to work 如何创建可以接受满足 std::forward_iterator 的任何类型的模板类<T>在构造函数中? - How do I create a template class that can accept any type that satisfies std::forward_iterator<T> in the constructor? 如何将类型T的值分配给uchar类型的data [i]而没有任何损失? - How to assign a value of type T to data[i] of type uchar without any loss? 将T的数组存储在结构T中时,类型错误 - Incomplete type error when store an array of T in the struct T 我如何制作和填充枚举类型的数组 - How do I make and fill and array of enum type 如何创建 char C++ 类型的指针数组? - How do I create an array of pointers of type char C++? 如何添加枚举类型以引用数组 - How do I add an enumeration type to reference an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM