将字符串添加到vector的vector中
adding strings to a vector of vector
我试图将字符串添加到字符串的向量的向量的末尾,不知何故遇到内存问题。
我的代码类似于这个
vector<vector<string>> slist;
....
slist.push_back(vector1);
slist.push_back(vector2);
...
for(int i=0; i<10; i++){
int length = slist.size()-1;
slist[length].push_back("String"); // also tried slist.back().push_back("S");
}
这给了我一个记忆问题
Invalid read of size 8
==2570== at 0x404D18: std::vector<std::string, std::allocator<std::string> >::push_back(std::string const&) (stl_vector.h:735)
==2570== by 0x403956: main (asm.cc:400)
==2570== Address 0xfffffffffffffff0 is not stack'd, malloc'd or (recently) free'd
==2570==
==2570==
==2570== Process terminating with default action of signal 11 (SIGSEGV)
==2570== Access not within mapped region at address 0xFFFFFFFFFFFFFFF0
==2570== at 0x404D18: std::vector<std::string, std::allocator<std::string> >::push_back(std::string const&) (stl_vector.h:735)
==2570== by 0x403956: main (asm.cc:400)
==2570==
谁能告诉我为什么?PS:很抱歉之前问得不好…
您给出的代码可以正常工作:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
void print(vector<vector<string>> s)
{
cout << "Lists:" << endl;
for (const auto& v : s)
{
cout << "List: ";
for (const auto& i : v)
{
cout << i << ", ";
}
cout << endl;
}
cout << "Done" << endl;
}
int main()
{
vector<vector<string>> slist;
slist.push_back(vector<string>());
slist.push_back(vector<string>());
print(slist);
const auto length = slist.size()-1;
slist[length].push_back("String"); // also tried slist.back().push_back("S");
print(slist);
}
编辑:是的,你甚至可以把它放入一个循环:
vector<vector<string>> slist;
print(slist);
for (auto i = 0; i < 7; ++i)
{
slist.push_back(vector<string>());
for (auto j = 0; j < 5; ++j)
{
slist[i].push_back("String[" + toStr(i) + "][" + toStr(j) + "]"); // also tried slist.back().push_back("S");
}
}
print(slist);
问题可能在别的地方。你的调试器说什么?
相关文章:
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- 有没有办法将字符串添加到 Vector 中,但前提是它尚不存在?->C++
- 连接和压缩标准::vector<std::字符串的最佳方法>
- C++ 无法将 std::vector<BYTE> 转换为字符串或字符数组
- 如何在C++中处理多维字符串 VECTOR 的字符?
- 如何检查 std::vector<std::string> 的元素是否以某个子字符串开头?
- "error: subscripted value is not an array, pointer, or vector",我正在使用字符串
- 从 vector<pair<string, int 中提取不包含 0 的字符串>>
- 如何确定字符串是否包含在 std::vector 的任何字符串中
- 检查一系列单词,形成一个文本文件,保存在字符串vector C 中
- 仅威胁唯一字符串 - 什么是更快的 vector<std::string> 或只是 std::string
- 检查 std::vector 中的字符串是否包含C++中的子字符串
- 如何将十六进制字符串分为std :: vector
- STD :: vector和std ::字符串重新分配策略
- C++ vector 中不存在的字符串成员变量
- cout错误地打印出字符串的Vector
- 无法将C风格的字符串推送到std::vector中
- std::vector中的字符串验证
- 从vector字符串中删除项
- 向vector字符串追加