我在将字符串值放入“字符串 vector 结构”时遇到了问题。 最简单的可重现代码如下:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
struct ttt {
string name;
unsigned int ID;
vector<unsigned int> numList;
};
int main() {
vector<ttt> b;
b.reserve(3);
b[0].ID = 1;
b[0].numList.push_back(3);
b[0].numList.push_back(4);
string dd ("Desk");
b[0].name = dd;
cout << b[0].ID << b[0].name << b[0].numList[2] << endl;
return 0;
}
代码可以编译,但无法将“Desk”字符串放入结构元素 b[0].name。现场出现Segmentation Fault。
我也尝试了以下几行,但都失败了。
b[0].name.push_back(dd);
b[0].name += dd;
我的编译器是 GCC g++ 4.7.7 20120313, 我使用了下面的编译命令。
/usr/bin/g++ --std=gnu++0x -Werror -Wall -Wextra -Warray-bounds
我们将不胜感激,真诚地提供任何帮助。
最佳答案
有两个错误:
直接分配 b[0]
而不调用 push_back
或事先在构造函数调用中初始化它。
另一个违规行是
b[0].numList[2]
因为您只调用了两次 push_back()
,并且索引是从 0 开始的。
像这样直接初始化 vector 会好得多:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
struct ttt {
string name;
unsigned int ID;
vector<unsigned int> numList;
};
int main() {
vector<ttt> b{{"Desk", 1, { 3, 4 }}};
cout << b[0].ID << b[0].name << b[0].numList[1] << endl;
}
关于C++将字符串放入字符串 vector 结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39273136/