c++ - 类型类的 vector (地址簿程序)

标签 c++ class vector

我正在开发一个地址簿程序,它从以下格式的 csv 文件中读取数据

“姓氏”、“名字”、“昵称”、“email1”、“email2”、“phone1”、“phone2”、“地址”、“网站”、“生日”、“备注”

我已经通过以下方式使用 getline 读取了文件:

   if(!input.fail())
     { 
       cout<<"File opened"<<endl;
       while(!input.eof())
       {

     getline(input,list) ; 
     contactlist.push_back(list);
     token=con.tokenize(list);  // NOT SURE IF I'm doing this right..am I?

        }
    }

我正在使用我的一个类联系人的 tokenize 成员函数,它看起来像这样

// member function reads in a string and tokenizes it
vector<string>Contact::tokenize(string line)
{
    int x = 0, y = 0,i=0;

string token;
vector<string>tokens;
while(x < line.length() && y < line.length())
{

    x = line.find_first_not_of(",", y);
    if(x >=0 && x < line.length())
    {

        y = line.find_first_of(",", x);
        token = line.substr(x, y-x);
        tokens.push_back(token);
        i++;
    }
}

}     

我现在需要将标记化 vector 读入另一个类的私有(private) vector 成员变量,并且还需要将它们读入名字、姓氏的单个私有(private)变量...类 Contact 的注释。如何将它们读入私有(private)变量类类型的 vector 成员变量,以及我如何在成员函数中调用它们来进行评估,例如使用 vector 添加联系人的排序。

我总共有 2 个头文件 Contact 和 addressbook 及其各自的实现文件和一个 main。

此外,如果您碰巧有一个清晰的概念来访问 vector 中的 vector/vector 中的 vector ,例如我在 main 中有 contactlist 和 token

最佳答案

首先,您应该将标记化函数与联系人类分开。读取 csv 行不是联系人的责任。因此,将此方法提取到一个新的分词器类中,只需编写一个免费的分词函数或使用类似 boost tokenizer 的解决方案.

使用生成的 token ,您可以创建联系人实例或将其传递给另一个类。

struct Contact
{
  std::string firstName, lastName, email;

  /// Constructor.
  Contact(const std::string& firstName, 
      const std::string& lastName, 
      const std::string& email);
};

struct AnotherClass
{
  /// Constructor.
  AnotherClass(const std::vector<std::string>& tokens) :
     privateVector(tokens)  {}

  /// Construction with input iterators
  template<typename Iter>
  AnotherClass(Iter firstToken, Iter lastToken) :
    privateVector(firstToken, lastToken) {}

private:
  std::vector<std::string> privateVector;
};


int main()
{
  std::string line = ReadLine();
  std::vector<std::string> tokens = tokenize(line);

  Contact newContact(tokens[0], tokens[1], tokens[2]);

  AnotherClass wathever(begin(tokens), end(tokens));
}

关于c++ - 类型类的 vector (地址簿程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10594948/

相关文章:

c++ - 在共享内存上分配原子

c++ - 使用 BLAS 和 LAPACKE 在 C++ 中使用 SVD 计算伪逆

c++ - 使用 CMake、DSO-Link-Change 链接失败

java - 如何在 eclipse、tomcat 和 stripes 下将 .java 文件更改传播为 .class

r - 在空白处分割字符串向量

java - 内存中的数据操作

c++ - 如何为 std::variant 编写 operator<<?

class - 为什么我可以将方法标记为隐式而不是构造函数?

javascript - 创建一个类并调用它的属性 (javascript)

c++ - 在模板类中折叠指针?