C++将字符串数组[]复制到vector <string>中

4

我正在编写一个类,其中包含一个成员函数“insert”,将字符串数组复制到类内容中,该内容是一个向量数组。

但是,这个终止错误一直弹出,说我超过了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;
    };


};

如果您需要更多信息,请随时询问!谢谢!
6个回答

8

实际上,您不需要自己复制它们。您可以使用std::vector::assign将转换为std::vector

vector::assign

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

示例

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/


2

使用 std::copy

#include <algorithm> //for std::copy
#include <iterator>  //for std::back_inserter

std::copy(_lines_, _lines_ + count, std::back_inserter(_contents));

其中count是数组中字符串的总数。如果字符串总数为56,则count应该是56,而不是55(如果您想将所有字符串复制到_contents中)。


1

这个向量没有大小(只是一些空间被reserve了)。

你可以使用resize()来调整向量的大小,或者使用push_back()添加新元素。


1

在使用下标 [] 运算符添加任何元素之前,您应该调整 vector <string> _contents 的大小。

另外:为您的 Map 类提供一个默认构造函数。


1
  1. 不应使用下划线前缀标识符
  2. 在初始化列表中分配_nameMap(string name) : _name(name) {
  3. _contents具有56个元素的足够容量,但没有实际元素。您应该调整它的大小(_contents.resize(56);),在Insert方法中添加元素(_contents.push_back(_lines_[I]);),或者使用足够的容量构造它(在初始化列表中添加, _contents(56))。

0

现在变得简单多了。(C++11)

string sArray[3] = {"aaa", "bbb", "ccc"};
vector<string> sVector (sArray, sArray + 3);

不需要复制,赋值即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接