【发布时间】: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 可以解决该问题,但我无法将字符串添加到向量中!
【问题讨论】:
-
row是vector<int>,它必须是std::vector<std::string> -
另外你为什么要在
row中添加整数?目的是什么(因为您显然想要字符串)? -
@UnholySheep 我现在在 row.push_back(j) 行上得到错误。因为 J 是一个整数。那么,如何在不使用 int 的情况下将列添加到新创建的行?
-
我显然误解了它在做什么。对此非常陌生
-
@DanJamesPalmer 为什么最后你认为存在
hops_vector[Hops]?如果Hops为 4,并且二维向量中的行数少于 5 行怎么办?这将导致越界访问。也许二维数组不是您想要的,而您真正应该使用的是std::map<std::string, std::vector<int>>,其中string是跳数,vector<int>是与字符串关联的整数向量?这将比 2D 数组和每次调用std::find更有意义(也更有效)。
标签: c++ arrays multidimensional-array vector push-back