我有一个循环通过一组很大的名字,下面有段错误,问题出在哪里?
void test(std::set<std::wstring> *names)
{
std::set<std::wstring>::iterator itr;
for (itr = names->begin(); itr != names->end(); ++itr)
{
std::wstring name = *itr;
}
}
错误:
Program received signal SIGSEGV, Segmentation fault. 0x00007fff84b62c54 in std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t>>::basic_string(std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > const&)> () from /usr/lib/libc++.1.dylib
答案 0 :(得分:0)
您展示的代码没有问题,正如MWE live at Ideone所示:
#include <iostream>
#include <set>
#include <string>
using namespace std;
void test(std::set<std::wstring> *names) {
std::set<std::wstring>::iterator itr;
for (itr = names->begin(); itr != names->end(); ++itr) {
std::wstring name = *itr;
}
}
int main() {
std::set<std::wstring> s{L"aasdasd", L"badsasd"};
test(&s);
return 0;
}
因此,问题是代码中的其他位置未显示。我建议使用gdb之类的调试器来查找正在发生的事情。例如。在Linux系统上:
g++ -g main.cpp -o main
gdb main
run
&gt;阅读堆栈跟踪作为旁注,for循环会更好,如果你不打算修改names
通过const引用(example here on Ideone)传递它:
#include <iostream>
#include <set>
#include <string>
using namespace std;
void test(const std::set<std::wstring> &names) {
for (auto&& name : names) {
std::wcout << name << std::endl;
}
}
int main() {
std::set<std::wstring> s{L"aasdasd", L"badsasd"};
test(s);
return 0;
}