c++ - 从类中返回一个字符串——奇怪的行为
问题描述
大约 10 年前,我对 C++ 编码有点兴趣,但从未真正爱上它。但是我现在的一个项目需要 c++(所以我对 c++ 有一点了解,但我不是专家)。我浏览了我的旧笔记和代码片段,让代码做我想做的事——除了一件事:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class B
{
private:
string ns;
public:
B(string ms) {ns = ms;}
string gets() {return ns;}
};
class A
{
private:
vector<B> nb;
public:
A(vector<B> mb) {nb = mb;}
vector<B> getb() {return nb;}
};
int main(int argc, char **argv)
{
B b0 = B("zero");
B b1 = B("one");
B b2 = B("two");
B b3 = B("three");
A a = A({b0, b1, b2, b3});
cout << endl << endl;
for(auto it = a.getb().begin(); it != a.getb().end(); ++it)
cout << it->gets() << " ";
return 0;
}
运行此代码 (g++ -std=c++11 main.cpp) 会导致
在抛出 'std::bad_alloc'
what() 的实例后调用终止:std::bad_alloc Aborted (core dumped)
错误。这已经很奇怪了,因为这基本上只是我笔记的副本(但是,它在笔记中返回一个整数而不是字符串)。如果我改为让函数返回ns.c_str()
它几乎可以工作,我得到
解决方案
每个getb()
ina.getb().begin()
并a.getb().end()
返回原始向量的单独副本。将来自一个向量的迭代器与来自另一个向量的迭代器进行比较是不好的。
你可以把你的getb()
方法改成这样。
const vector<B>& getb() const {return nb;}
现在begin()
andend()
调用将在同一个向量上工作。
或者使用更 c++11 友好的基于范围的 for 循环:
for (var b in a.getb()) {
cout << b.gets() << " ";
哪个.begin()
,.end()
和++
适合你。
如果你绝对想使用老式的 for 循环,而不是改变你的getb()
方法,你也可以这样做:
auto b_copy = a.getb();
for(auto it = b_copy.begin(); it != b_copy.end(); ++it)
cout << it->gets() << " ";
推荐阅读
- bash - 将 grep 匹配到 sed
- docker - Docker for Windows:可以安装打印机吗?
- algorithm - 找到长度为 K 的好的子串,使其重要性最小
- java - 从java中插入数据到oracle有问题
- java - 将 Bouncycastle 安全提供程序添加到 maven jar
- html - CSS:如何将图像放置在两列中,并带有换行文本?(包括图片供参考)
- python - AttributeError:模块 'pandas' 没有属性 'DataFrame'
- android - 当我在模拟器上运行应用程序时,Android Studio 文本不符合 layout_margin
- python - 对列表列表
- asp.net-mvc - ASP.NET Core Capturing POST data