![](/img/trans.png)
[英]Segmentation fault while initializing vector by an initialized array in C++
[英]Segmentation fault while declaring vector string array C++
#include<iostream>
#include<string>
#include<stdio.h>
#include<stdlib.h>
//#include<set>
#include<list>
#include<cmath>
//#include<algorithm>
#include<fstream>
#include<vector>
#define max 10000.0
using namespace std;
int main()
{
int n;//number of rooms
cin>>n;
vector<string> room_name(n,"");
for(int i=0;i<n;i++)
{
string tmp;
cin >> tmp;
room_name.push_back(tmp);
}
}
錯誤分段錯誤:仍然出現11。
無法找到錯誤點。 知道為什么會這樣嗎?
聲明向量是不夠的:與數組不同,它可以增長,因此默認情況下它以零的固定大小開始。
如果您預先知道向量的大小,則可以請求特定大小的向量(也可以在此之后進行擴展)
vector<string> room_name(n, ""); // You can supply a different default, or no default here
這樣就形成了一個由100個空字符串組成的向量,使您可以在后續循環中訪問元素0..n-1。
另外,您可以使用push_back
使向量一次增加一個元素,如下所示:
for(int i=0;i<n;i++)
{
string tmp;
cin >> tmp;
room_name.push_back(tmp);
}
除非向量已經確定大小,否則您需要使用push_back
附加到向量的末尾。
std::vector<int> foo;
for (int i = 0; i < 10; ++i)
{
foo.push_back(i);
}
否則,您需要確保矢量已調整大小,或者
std::vector<int> foo(10);
要么
std::vector<int> foo;
foo.resize(10);
然后您可以像以前一樣使用索引
for (int i = 0; i < 10; ++i)
{
foo[i] = i;
}
如果嘗試在調整數組大小之前寫入每個索引,則表示寫入內存超出范圍。
您確實要在向量中手動輸入1000個字符串嗎?:)
用大寫字母定義即時名稱也是一個好主意。 所以代替
#define max 10000.0
最好寫
#define MAX 10000.0
尚不清楚為什么將max定義為浮點數而不是整數。
考慮到變量n尚未在程序中聲明。 因此程序無法編譯。 也許您的意思是max而不是n。
由於向量被定義為空向量
vector<string> room_name;
也就是說,它沒有元素,則可能無法使用下標運算符在向量中輸入值。
您可以使用方法push_back代替以下方式
vector<string> room_name;
room_name.reserve( n );
for ( int i = 0; i < n; i++ )
{
string s;
cin >> s;
room_name.push_back( s );
}
並且可以使用標頭<algorithm>
聲明的標准算法std::copy_n
代替循環
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#define N 2
int main()
{
std::vector<std::string>room_name;
room_name.reserve( N );
std::copy_n( std::istream_iterator<std::string>( std::cin ), N,
std::back_inserter( room_name ) );
for ( const std::string &s : room_name ) std::cout << s << std::endl;
return 0;
}
如果輸入字符串
my_room
your_room
然后程序將從矢量輸出它們
my_room
your_room
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.