gpt4 book ai didi

C++ 将字符串数组 [] 复制到 vector

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:00:35 25 4
gpt4 key购买 nike

所以我正在使用成员函数“插入”创建此类,以从字符串数组复制到作为 vector 数组的类内容。

这个中止错误不断弹出,说我正在越过 Vector 端,但我不明白为什么......

代码如下:

/////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// Map class /////////////////////
class Map
{
private:
/////////////////////////////////////////// Map Variables ///////////////
string _name;
vector <string> _contents;

public:
Map(string name){_name = name;
_contents.reserve(56);};
~Map(){};
string getName()
{
return _name;
};

vector <string> getContents()
{
return _contents;
};

/////////////////////////////////////////// Insert ////////////////////////
// string* to an array of 56 strings;
bool Insert(string* _lines_)
{

for (int I = 0; I < 3; I++)
{
_contents[I] = _lines_[I];
}
return true;
};


};

如果您需要更多信息,请询问! 谢谢!

最佳答案

实际上,您不需要自己复制它们。您可以使用 std::vector::assignc 样式数组 转换为 std::vector

vector::赋值

将新内容分配给 vector 对象,在调用之前删除 vector 中包含的所有元素,并用参数指定的元素替换它们。

示例

string sArray[3] = {"aaa", "bbb", "ccc"};
vector<string> sVector;
sVector.assign(sArray, sArray+3);
^ ok, now sVector contains three elements, "aaa", "bbb", "ccc"

更多详情

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

关于C++ 将字符串数组 [] 复制到 vector <string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5839499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com