好吧,我想弄清楚一個問題,當我嘗試下面這段代碼:char *爲什麼不復制到矢量中但字符串被複制?
#include <iostream>
#include <vector>
#include <stdint.h>
#include <string>
#include <Windows.h>
using namespace std;
int main(){
vector<char*> v;
char s[10];
std::cout << "Enter Values :\n";
for (int i = 0; i<5; i++){
cin >> s;
v.push_back(s);
}
std::cout << "\n\n\nPrinted Values :\n";
for (auto ss : v){
cout << ss << "\n";
cout << "------------\n";
}
system("pause");
return 0;
}
這是我收到的輸出:
Enter Values :
aaaa
ssss
ddddd
ffff
errrr
Printed Values :
errrr
------------
errrr
------------
errrr
------------
errrr
------------
errrr
------------
但現在我改變了「字符*」以 「串」:
#include <iostream>
#include <vector>
#include <stdint.h>
#include <string>
#include <Windows.h>
using namespace std;
int main(){
vector<string> v;
string s;
std::cout << "Enter Values :\n";
for (int i = 0; i<5; i++){
cin >> s;
v.push_back(s);
}
std::cout << "\n\n\nPrinted Values :\n";
for (auto ss : v){
cout << ss << "\n";
cout << "------------\n";
}
system("pause");
return 0;
}
現在,它存儲所有的入載體:
Enter Values :
aaaa
ssss
ddddd
ffff
errrr
Printed Values :
aaaa
------------
ssss
------------
ddddd
------------
ffff
------------
errrr
------------
我的問題是,爲什麼char *沒有存儲在向量中,但字符串存儲在向量中?
'char *'只是一個指針,而'std :: string'是一個類。數組不會自動複製。 –