C ++ 98中的容器初始化

时间:2017-06-30 07:59:54

标签: c++ stl c++98

我必须使用以下规则构造一个有序容器(必须是可迭代的):

  

如果条件为真,则容器为{1,0},否则为{0,1}

我有以下代码,但我发现它并不“优雅”:

   vector<int> orderedSides;
   if (condition) 
   {
       orderedSides.push_back(1);
       orderedSides.push_back(0);
   }
   else            
   {
       orderedSides.push_back(0);
       orderedSides.push_back(1);
   }

有没有更好的方法(从简洁和性能的角度来看)?

6 个答案:

答案 0 :(得分:16)

您可以实现以下内容:

public class LocationUtil extends Service implements LocationListener {
    private static final String TAG = LocationUtil.class.getSimpleName();

    public Context mContext;

    // flag for GPS status
    private boolean isGPSEnabled = false;
    // flag for network status
    private boolean isNetworkEnabled = false;
    // flag for passive status
    private boolean isPassiveEnabled = false;

    private boolean canGetLocation = false;

    private Location location; // location
    private double latitude; // latitude
    private double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 0;
    // Declaring a Location Manager
    protected LocationManager locationManager;

    public LocationUtil(Context context) {
        this.mContext = context;
        getLocation();
    }

    public LocationUtil() {
    }

    public Location getLocation() {
        try {
            location = null;
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            // getting passive status
            isPassiveEnabled = locationManager
                    .isProviderEnabled(LocationManager.PASSIVE_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled && !isPassiveEnabled) {
                showSettingsAlert();
            } else {
                this.canGetLocation = true;
                if (checkPermission()) {
                    if (isNetworkEnabled) {
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d(TAG, "Network");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                                return location;
                            }
                        }
                    }
                    // if GPS Enabled get lat/long using GPS Services
                    if (isGPSEnabled) {
                        if (location == null) {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d(TAG, "GPS Enabled");
                            if (locationManager != null) {
                                location = locationManager
                                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
                                    return location;
                                }
                            }
                        }
                    }
                    if (isPassiveEnabled) {
                        if (location == null) {
                            locationManager.requestLocationUpdates(
                                    LocationManager.PASSIVE_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d(TAG, "Passive Enabled");
                            if (locationManager != null) {
                                location = locationManager
                                        .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
                                    return location;
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(LocationUtil.this);
        }
    }

    private boolean checkPermission() {
        int permission = ContextCompat.checkSelfPermission(mContext, ACCESS_FINE_LOCATION);
        if (permission == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");
        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
        getLocation();
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        getLocation();
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

比明确的 if 子句稍短。

正如下面提到的@Deduplicator,我们可能会以更简洁的方式重写第二行:

vector<int> orderedSides(2, 0);
(condition ? orderedSides.front() : orderedSides.back()) = 1;

答案 1 :(得分:5)

QGraphicsView

我认为它不是更高效,但我发现它更优雅。

答案 2 :(得分:1)

你可以在效率和避免重复之间做出妥协,先用条件初始化第一个,然后用第一个初始化第二个。

vector<int> orderedSides(1, bool(condition)) ;
orderedSides.push_back(!orderedSides.back());

答案 3 :(得分:0)

ln -s ~/Desktop

我知道这需要花费一些成本。作为候选人之一。

答案 4 :(得分:0)

您可以从数组中填充std::vector,即使在C ++ 98中也是如此。

以下是一个例子:

#include <iostream>
#include <vector>

int main() {
    bool condition = false;
    std::cout << "condition is: " << std::boolalpha << condition << '\n';

    int arr[][2] = {{0,1}, {1,0}};
    int index = condition;
    std::vector<int> v(arr[index], arr[index]+2);

    for (int i = 0; i < v.size(); i++)
        std::cout << v[i] << ' ';
    std::cout << '\n';
}

输出结果为:

$ g++ tt.cc && ./a.out
condition is: false
0 1 

供参考:

答案 5 :(得分:0)

如果构建元素(问题中的int,无论现实生活中的是什么)都是免费且无副作用的:

static const int data[] = { 0, 1, 0 };
std::vector<int> orderedSides (data+condition, data+condition+2);

完整的程序示例:

#include <iostream>
#include <vector>

std::vector<int> make(bool cond)
{
    static const int data[] = { 0, 1, 0 };
    return std::vector<int> (data+cond, data+cond+2);
}

std::ostream& operator<<(std::ostream& os, const std::vector<int>& v)
{
    return os << "{ " << v[0] << ", " << v[1] << " }";
}    

int main()
{
    std::cout << "true:  " << make(true) << "\n"
              << "false: " << make(false) << "\n";
}

打印:

true:  { 1, 0 }
false: { 0, 1 }

Demo