C ++遍历结构体列表

时间:2018-10-14 10:53:59

标签: c++ list struct

在访问结构体中的结构体列表时遇到问题:

struct  B{
  string word;
};

struct A{
  list<B> message;
};

将数据放入数据结构中没问题:

list<A> messageList;
while(--there are messages to be found--){
  list<B> wordList;
  do{
    string buff;
    wordList.push_front({buff});
  }while(--there are words to be found--);
  messageList.push_front({wordList});
}

但是知道我想阅读消息中的每个单词:

list<A>::iterator itMessage;
for(itMessage = messageList.begin(); itMessage != messageList.end(); itMessage++){

在这里我被卡住了,我是否要用迭代器做一个迭代器?

  list<itMessage->message>::iterator itWord;

还是列表中的列表?

  list<list<??>>::iterator itWord;

1 个答案:

答案 0 :(得分:3)

首先,遍历消息,然后遍历单词:

DBHelper ——

package com.example.user.model.Database;

import android.content.ContentValues;
import android.content.Context;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


import com.example.user.model.User;
import com.example.user.model.UserProfile;

import java.util.ArrayList;
import java.util.List;

public class DBHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "user_detail.db";




    public DBHelper(Context context) {
        super(context,DATABASE_NAME,null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + UserProfile.User.TABLE_NAME + "("+UserProfile.User.col_1+" Integer primary key autoincrement," +
                "" +UserProfile.User.col_2 + " text," +
                ""+UserProfile.User.col_3+ " text," +
                ""+UserProfile.User.col_4+ " text," +
                ""+UserProfile.User.col_5+ " text )");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) {
        db.execSQL(("drop table if exists " + UserProfile.User.TABLE_NAME));
        onCreate(db);
    }
    public boolean addInfo(String userName,String password){
        SQLiteDatabase db= this.getWritableDatabase();
        ContentValues con=new ContentValues();
        //con.put(col_1,ID);
        con.put(UserProfile.User.col_2,userName);
        con.put(UserProfile.User.col_5,password);
        //con.put(col_3,dateOfBirth);
        //con.put(col_4,Gender);

        long result=db.insert(UserProfile.User.TABLE_NAME,null,con);
        db.close();
        if(result==-1){
            return false;
        }else{
            return true;
        }
    }
    public boolean updateInfor(String username,String dateOfBirth,String gender, String password){


        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues con= new ContentValues();
        //con.put(UserProfile.User.col_1,userId);
        con.put(UserProfile.User.col_2,username);
        con.put(UserProfile.User.col_3,dateOfBirth);
        con.put(UserProfile.User.col_5,password);
        con.put(UserProfile.User.col_4,gender);

        db.update(UserProfile.User.TABLE_NAME,con,UserProfile.User.col_2+"=?",new String[]{String.valueOf(username)});
       // db.close();



        return true;


    }
    public Integer DeleteInfor(String userName){
        SQLiteDatabase db=this.getReadableDatabase();


        return db.delete(UserProfile.User.TABLE_NAME,UserProfile.User.col_2+"=?",new String[]{userName});

    }
    public Cursor getData(){
        SQLiteDatabase db= this.getWritableDatabase();
        Cursor res=db .rawQuery(("select * from "+UserProfile.User.TABLE_NAME ),null);
        return  res;
    }
    public List<User> getAllUser(String users){
        String[] columns={
                UserProfile.User.col_1,
                UserProfile.User.col_2,
                UserProfile.User.col_3,
                UserProfile.User.col_4,
                UserProfile.User.col_5,
        };
        String sortOrder=UserProfile.User.col_1 +"ASC";

        List<User>userList = new ArrayList <User>();
        SQLiteDatabase db= this.getReadableDatabase();

        Cursor cursor = db.query(UserProfile.User.TABLE_NAME,
                columns,
                null,
                null,
                null,
                null,
                sortOrder);

        if(cursor.moveToFirst()){
            do{
                User user= new User();
                user.setUserId(cursor.getString(cursor.getColumnIndex(UserProfile.User.col_1)));
                user.setUserName(cursor.getString(cursor.getColumnIndex(UserProfile.User.col_2)));
                user.setDateOfBirth(cursor.getString(cursor.getColumnIndex(UserProfile.User.col_3)));
                user.setGender(cursor.getString(cursor.getColumnIndex(UserProfile.User.col_4)));
                user.setPassword((cursor.getString(cursor.getColumnIndex(UserProfile.User.col_5))));
                userList.add(user);
            }while (cursor.moveToNext());
        }
        cursor.close();
        db.close();

        return userList;
    }
    public boolean checkUser(String username){
        String[] columns={UserProfile.User.col_1};

        SQLiteDatabase db=this.getReadableDatabase();
         String selection  = UserProfile.User.col_2+"=?";

         String [] selectionArgs={username};

         Cursor cursor=db.query(UserProfile.User.TABLE_NAME,
                 columns,
                 selection,
                 selectionArgs,
                 null,
                 null,
                 null);
         int cursorCount=cursor.getCount();
         cursor.close();
         db.close();

         if(cursorCount>0){
             return true;
         }

        return false;
    }
    public boolean checkUsers(String username,String password) {
        String[] columns={UserProfile.User.col_1};

        SQLiteDatabase db=this.getReadableDatabase();
        String selection  = UserProfile.User.col_2+"=? and "+UserProfile.User.col_5 +"=?";

        String [] selectionArgs={username,password};

        Cursor cursor=db.query(UserProfile.User.TABLE_NAME,
                columns,
                selection,
                selectionArgs,
                null,
                null,
                null);
        int cursorCount=cursor.getCount();
        cursor.close();
        db.close();

        if(cursorCount>0){
            return true;
        }

        return false;
    }



}


Edit——


package com.example.user.model;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.user.model.Database.DBHelper;

import java.util.ArrayList;
import java.util.List;

public class EditProfile extends AppCompatActivity {
    EditText username, dob, password;
    RadioButton male, female;
    Button edit, delete, search;
    String gender;
    RadioGroup radiogroup;
    DBHelper db;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);

        db = new DBHelper(this);

        username = findViewById(R.id.txtUserName);
        dob = findViewById(R.id.txtDOB);
        password = findViewById(R.id.txtPassword);

        male = findViewById(R.id.radiomale);
        female = findViewById(R.id.radioFemale);

        edit = findViewById(R.id.btn_Edit);
        delete = findViewById(R.id.btn_Delete);
        search = findViewById(R.id.buttonSearch);

        radiogroup= findViewById(R.id.radioGroup);

        radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group,int checkedId) {
                if(checkedId==R.id.radioFe){
                    gender="Female";
                }else{
                    gender="male";
                }
            }
        });

        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String user = username.getText().toString().trim();
                final String pass = password.getText().toString().trim();
                final String bd = dob.getText().toString().trim();



                boolean count = db.updateInfor(user,bd,gender,pass);

                if (count == true) {
                    Toast.makeText(EditProfile.this,"Updated",Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(EditProfile.this," Not Updated",Toast.LENGTH_LONG).show();
                }


            }
        });


        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String user = username.getText().toString().trim();
                int count = db.DeleteInfor(user);
                if (count > 0) {
                    Toast.makeText(EditProfile.this,"Delete Succesful",Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(EditProfile.this,"Delete doesn't work",Toast.LENGTH_LONG).show();
                }
            }
        });

        search.setOnClickListener(new View.OnClickListener()

    {
        @Override
        public void onClick (View v){
        Cursor res = db.getData();
         if(res.getCount()==0){
        Toast.makeText(EditProfile.this,"No records",Toast.LENGTH_LONG).show();
        }
        StringBuffer buffer = new StringBuffer();
        while (res.moveToNext()) {
            buffer.append("User name :" + res.getString(1)+"\n");
            buffer.append("Date of birth :"+res.getString(2)+"\n");
            buffer.append("Gender :"+ res.getString(3)+"\n");
            buffer.append("Password :"+res.getString(4)+"\n\n\n");

        }
            showMessage("Registered users  \n",buffer.toString());
    }});


}


    public void RadioButtonClicked(View view){
        boolean checked=((RadioButton)view).isChecked();
        switch (view.getId()){
            case R.id.radiomale:
                if(checked){
                    gender="Male";
                }
                break;
            case R.id.radioFemale:
                if(checked){
                    gender="Female";
                }
                break;



        }

    }
    public void showMessage(String title,String Message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();
    }



}



Home — 

package com.example.user.model;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.user.model.Database.DBHelper;

import java.util.ArrayList;

public class Home extends AppCompatActivity {

    private Button Register,Login;
    private EditText userName;
    private EditText password;
    DBHelper db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        Register = (Button) findViewById(R.id.btnRegister);
        Login=(Button)findViewById(R.id.btnLogin);
        db=new DBHelper(this);

        Register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userName=(EditText)findViewById(R.id.txtUserName);
                String name=userName.getText().toString();
                password=(EditText)findViewById(R.id.txtPassword);
                String pass=password.getText().toString();
                if(name.matches("")||pass.matches("")){
                    Toast.makeText(Home.this,"Fields cannot be empty",Toast.LENGTH_LONG).show();
                }else {

                    boolean isInserted=db.addInfo(userName.getText().toString(),password.getText().toString());
                    if(isInserted==true){
                        Toast.makeText(Home.this,"Succesfully registered",Toast.LENGTH_LONG).show();

                    }else{
                        Toast.makeText(Home.this,"Failed in  registering",Toast.LENGTH_LONG).show();
                    }


                    }



                }

        });

        Login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String user = userName.getText().toString().trim();
                String pass = password.getText().toString().trim();

                if(!user.matches("") && (!pass.matches(""))){
                    if (db.checkUsers(user,pass)) {


                        Intent intent = new Intent(Home.this,ProfileManagement.class);
                        startActivity(intent);

                    }else{
                        Toast.makeText(Home.this,"Register first",Toast.LENGTH_LONG).show();
                    }
               }else{
                    Toast.makeText(Home.this,"Fill the fields ",Toast.LENGTH_LONG).show();
                }

                }
        });

    }


}


Manifest—


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.user.model">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Home">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ProfileManagement" />
        <activity android:name=".EditProfile" />
    </application>

</manifest>



Profile mgt ——


package com.example.user.model;

import android.content.Intent;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.example.user.model.Database.DBHelper;

import java.util.ArrayList;

public class ProfileManagement extends AppCompatActivity {

    Button Update;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_management);


        Update=findViewById(R.id.btnUpdate);
        Update.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   Intent intent= new Intent(ProfileManagement.this,EditProfile.class);
                   startActivity(intent);
                }
            });




    }

    public void RadioButtonClicked(View view) {
    }
}


User—


package com.example.user.model;

public class User {

    private String userId;
    private String userName;
    private String dateOfBirth;
    private String gender;
    private String password;

    public User(){

    }

    public String getUserId(){
        return userId;
    }
    public void setUserId(String userId){
        this.userId=userId;
    }
    public String getUserName(){
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getDateOfBirth(){
        return dateOfBirth;
    }

    public void setDateOfBirth(String dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


}



Userprofile---

package com.example.user.model;

import android.provider.BaseColumns;

public final class UserProfile {

    private UserProfile(){

    }
    public static class User implements BaseColumns{
        public static final String TABLE_NAME = "user_details";
        public static final String col_1 = "ID";
        public static final String col_2 = "userName";
        public static final String col_3 = "dateOfBirth";
        public static final String col_4 = "Gender";
        public static final String col_5 = "password";
    }
}


Values---

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

如果您想在struct A { auto begin() { return message.begin(); } auto end() { return message.end(); } list<B> message; }; for (auto& message : messageList) for (auto& word : message) { ... } 中的单词上使用单个迭代器,则必须自己编写。