此代碼只是一個原型,如何我希望我的輸出..
我的計劃應該能夠焦炭矢量的特定索引中插入字符;
該程式適用于 vector<vector<int>>
#include<bits/stdc .h>
using namespace std;
int main()
{
vector<vector<string>>v;
for(auto i=0;i<5;i )
v.emplace_back(vector<string>());
v[0].emplace_back('z');
v[1].emplace_back('r');
v[0].emplace_back('x');
v[1].emplace_back('g');
for(auto i:v){
for(auto j:i)
cout<<j<<" ";cout<<endl;}
return 0;
}
我的預期輸出:
z x
r g
錯誤:
no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(char)’ { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
uj5u.com熱心網友回復:
看來你需要像下面這樣的東西
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::vector<std::string>> v( 2 );
v[0].emplace_back( 1, 'z' );
v[1].emplace_back( 1, 'r' );
v[0][0].append( 1, ' ' );
v[1][0].append( 1, ' ' );
v[0][0].append( 1, 'x' );
v[1][0].append( 1, 'g' );
for ( const auto &item : v )
{
std::cout << item[0] << '\n';
}
return 0;
}
程式輸出是
z x
r g
否則像這樣宣告向量
std::vector<std::vector<char>> v;
例如
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::vector<char>> v( 2 );
v[0].emplace_back( 'z' );
v[1].emplace_back( 'r' );
v[0].emplace_back( 'x' );
v[1].emplace_back( 'g' );
for ( const auto &line : v )
{
for ( const auto &item : line )
{
std::cout << item << ' ';
}
std::cout << '\n';
}
return 0;
}
uj5u.com熱心網友回復:
您正在嘗試將字符(字符)存盤在 C 忽略的字串向量中。
您應該做的是將字串存盤在字串容器中(在這種情況下為向量)
#include<bits/stdc .h>
using namespace std;
int main()
{
vector<vector<string>>v;
for(auto i=0;i<5;i )
v.emplace_back(vector<string>());
v[0].emplace_back("z"); // here you are doing 'z' that is a character instead
v[1].emplace_back("r"); // use "z" which signifies a string
v[0].emplace_back("x");
v[1].emplace_back("g");
for(auto i:v){
for(auto j:i)
cout<<j<<" ";
cout<<endl;
}
return 0;
}
繼續編碼 繼續熱愛 C
PS:如果你只是使用向量和字串,只有一個建議只包含它們
# include <vector>
# include <string>
因為#include<bits/stdc .h>包含了很多東西
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/334852.html
