【问题标题】:Dynamically adding a row to a std::string 2d vector array向 std::string 二维向量数组动态添加一行
【发布时间】:2017-03-18 18:52:36
【问题描述】:

我正在尝试创建一个动态 2d std::string 向量,但在添加新行时遇到问题:

std::vector<std::vector<std::string>> hops_vector;

int Hop = 0;

for (Hop = 0; Hop < RouteHops; Hop++)
{
    char HopIPString[20];
    HopIPString[0] = 0;
    RouteTestGetHopTimedOut(TestHandle, Hop, &HopTimedOut);
    std::string thehop = std::to_string(Hop + 1);

    //If the hop hasn't been registered yet
    if (hopsstring.find(thehop) == std::string::npos) {
        vector<int> row; // Create an empty row
        hopsstring += thehop+","; // Add hop number to hop string

        //Add columns for pings per hop + IP and Loss/No Loss
        for (int j = 0; j < PingsPerHop+2; j++) {
            row.push_back(j); // Add an element (column) to the row
        }

        hops_vector.push_back(row); // Add the row to the main vector
        hops_vector[Hop][0] = thehop;
    }
}

hops_vector.push_back(row); 行给了我一个没有过载错误的实例。我假设因为 hops_vector 是一个 std::string 向量。将其更改为 int 可以解决该问题,但我无法将字符串添加到向量中!

【问题讨论】:

  • rowvector&lt;int&gt;,它必须是 std::vector&lt;std::string&gt;
  • 另外你为什么要在row 中添加整数?目的是什么(因为您显然想要字符串)?
  • @UnholySheep 我现在在 row.push_back(j) 行上得到错误。因为 J 是一个整数。那么,如何在不使用 int 的情况下将列添加到新创建的行?
  • 我显然误解了它在做什么。对此非常陌生
  • @DanJamesPalmer 为什么最后你认为存在hops_vector[Hops]?如果Hops 为 4,并且二维向量中的行数少于 5 行怎么办?这将导致越界访问。也许二维数组不是您想要的,而您真正应该使用的是std::map&lt;std::string, std::vector&lt;int&gt;&gt;,其中string 是跳数,vector&lt;int&gt; 是与字符串关联的整数向量?这将比 2D 数组和每次调用 std::find 更有意义(也更有效)。

标签: c++ arrays multidimensional-array vector push-back


【解决方案1】:

来自cmets:

修复编译器错误的简单方法是将vector&lt;int&gt; row; 替换为std::vector&lt;std::string&gt; row(PingsPerHop+2, "");(这会创建一个用“空”字符串填充的向量)并删除试图填充它的for 循环。

但是,正如@PaulMcKenzie 指出的使用std::map&lt;std::string, std::vector&lt;int&gt;&gt; 的不同方法,字符串是跳数,而向量包含与其相关的整数,(很可能)是一种更好的方法(在效率和概念上)

【讨论】:

    猜你喜欢
    • 2014-06-15
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2020-06-18
    相关资源
    最近更新 更多