C ++复制一个字符串数组[]对矢量<串GT; [英] C++ copying a string array[] to a vector <string>

查看:156
本文介绍了C ++复制一个字符串数组[]对矢量<串GT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使这个类的成员函数插入从字符串数组中的类内容是一个矢量数组复制。

So i'm making this class with a member function "insert" to copy from a string array to the classes contents which is a vector array.

此终止错误不断弹出说我要去过去的矢量结束,但我不明白为什么....

This abort error keeps popping up saying i'm going past the Vector end, but i don't understand why....

这里的code:

/////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////      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;
    };


};

如果您需要任何更多的信息只问! 谢谢!

If you need any more info just ask! Thanks!

推荐答案

其实,你并不需要自己复制它们。您可以使用的std ::矢量::分配 C数组转换为的std ::矢量

Actually, you don't need copy them yourself. You can use std::vector::assign to convert a c-style array to an std::vector.

向量::分配

分配新内容的矢量对象,丢弃所有包含在呼叫之前的向量元素和由那些由参数指定的替换它们。

Assigns new content to the vector object, dropping all the elements contained in the vector before the call and replacing them by those specified by the parameters.

示例

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

详细信息

<一个href=\"http://www.cplusplus.com/reference/stl/vector/assign/\">http://www.cplusplus.com/reference/stl/vector/assign/

这篇关于C ++复制一个字符串数组[]对矢量&lt;串GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆