将向量的元素推向左侧

时间:2018-02-03 19:42:39

标签: c++ vector

31 04 00 08

假设这是输入矢量文件:

我该如何生成?

31 48 00 00

我想推送来自' 04'的所有非零数字。向左转。请帮忙!!

3 个答案:

答案 0 :(得分:1)

您可以使用以下内容在向量中单次传递:

vector<int> v = {3, 1, 0, 4, 0, 0, 0, 8};
auto zero_iter = find(v.begin(), v.end(), 0);
for (auto curr_iter = zero_iter; curr_iter != v.end(); curr_iter++) {
    if (*curr_iter != 0) {
        swap(*curr_iter, *zero_iter);
        zero_iter++;
    }
}

这会使用std::find中的std::swap<algorithm>

这里的想法是跟踪第一个可用零位置的位置,并在此之后找到非零位置。每次找到非零数字时,都会将其交换到第一个可用的零位置,并将零位置增加到指向下一个位置。

答案 1 :(得分:1)

至少在我看来,到目前为止所提供的解决方案有点不合理。

标准库提供专门为手头任务设计的算法。您尝试将输入分区为非零数字,然后是零。为此,std::stable_partition可以很好地工作:

std::string input = "31040008";

std::stable_partition(input.begin(), input.end(),
    [](auto c) { return c != '0'; });

结果:

31480000

如果您不关心非零数字的顺序(只是它们都在零之前),您可以通过使用std::partition获得一点速度。

答案 2 :(得分:0)

您可以使用class CustomLaunchScreenVC : UIViewController { override func viewDidAppear(_ animated: Bool) { checkIfSignedIn() } func checkIfSignedIn(){ let uid = defaults.integer(forKey: "uid") let session = defaults.string(forKey: "session") if uid != nil && session != nil { loginWithSession(session: session, uid: uid) { response in if let response = response { if (response!.loggedIn == "yes"){ self.goToMainVC() } else { self.goToLoginVC() // This does NOT work, UIButtons' labels are NOT loading, and I don't know why :( } } } } else { // there is no saved session so user is not logged in self.goToLoginVC() // This does works, UIButtons' labels are loading } } func loginWithSession(session: String, uid: Int, completion: @escaping (CustomTypeArray??)->()){ let connectUrl = URL(string: "http://website.com/common/php/sessionLogin.php") var request = URLRequest(url: connectUrl!) request.httpMethod = "POST" let postString = "userId=\(uid)&session=\(session)" request.httpBody = postString.data(using: String.Encoding.utf8) let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in //Simplified the code if (data.loggedin == "yes"){ return completion(CustomTypeArray(loggedIn : "yes")) } else { return completion(CustomTypeArray(loggedIn : "no")) } } task.resume() } func goToLoginVC(){ let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC self.present(loginVC, animated: false) } func goToMainVC(){ let mainVC = self.storyboard?.instantiateViewController(withIdentifier: "MainVC") as! MainVC self.present(mainVC, animated: false) } } 删除所有0。实际上它只会将所有非零的元素向左推,并返回要删除的部分的开头。但是不是擦除,而是用0填充它:

std::remove

打印:

#include <iostream>
#include <vector>
#include <algorithm>


int main()
{
    std::vector<int> v = { 3, 1, 0, 4, 0, 0, 0, 8 };
    std::fill(std::remove(v.begin(), v.end(), 0), v.end(), 0);


    //test
    for (auto d : v)
        std::cout << d << " ";
    std::cout << std::endl;

    return 0;
}