字符串向量(从键盘读取)

时间:2019-05-15 08:43:25

标签: c++ string vector

我有一个电话簿程序,我想通过输入参数来改进它 从键盘读取的字符串向量中。

我尝试了这段代码,但是参数在矢量中无法识别;

string firstname, lastname, country, city, street;
string phone;
vector<string> user( firstname, lastname, country, city, street, phone);

2 个答案:

答案 0 :(得分:3)

您可以像这样使用初始化程序列表构造函数(https://en.cppreference.com/w/cpp/container/vector/vector#7):

#include <string>
#include <vector>

using std::string;
using std::vector;

int main()
{
  string firstname, lastname, country, city, street;
  string phone;
  vector<string> user{ firstname, lastname, country, city, street, phone };

  return 0;
}

答案 1 :(得分:0)

在将字符串添加到向量之前,是否使用值初始化字符串?您如何阅读它们?通过代码,我假设您遍历一个带有std :: cin的向量来获取值。如果是这样-将指针传递给向量而不是值。

/*vec declaration*/
std::string firstname, lastname, country, city, street, phone;
std::vector<std::string*> user{ &firstname, &lastname, &country, &city, &street, &phone};
...
/*reading*/
for(auto i : user)
    std::cin >> *i;
...
/*then you can access them from the desired string*/
std::cout << firstname; // will print firstname that you've read

建议1:如果知道容器的大小,请使用array / std :: array。当您知道容器大小会增加(添加/删除新元素)时,应使用向量。

SUGGESTION2:最好是为用户使用一种结构-以后管理和阅读代码都比较容易,所以f.ex:

struct User
{
    std::string firstname,
                lastname,
                country,
                city,
                street,
                phone;
}

然后使用vector将所有用户存储在一个容器中。如果您更容易以这种方式阅读辅助矢量,则可以始终像现在这样使用辅助矢量。