小编Ele*_*nts的帖子

如何使用 std::move 和后插入器将 std::list 中的元素移动到末尾?

在我的 std::list 中,我有 10 个元素,我想将数字 1000 移到列表的后面。

https://leetcode.com/playground/gucNuPit

有没有更好的方法,使用 std::move、后插入器或任何其他 C++ 语法的 1 行有意识地实现此目的?

// Move the number 1000 to the end of the list

#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
int main() {
    
    list<int> myList({2,3,4,1000,5,6,7,8,9,10});
    
    cout << "List before " << endl;
    for(auto e : myList)
        cout << e << " ";
    
    // get iterator to the number 1000 in the list
    list<int>::iterator findIter = std::find(myList.begin(), myList.end(), 1000);

    int val_to_move_to_end = *findIter;
    
    myList.erase(findIter);
    
    myList.push_back(val_to_move_to_end);
    
    cout << …
Run Code Online (Sandbox Code Playgroud)

c++ stl move rvalue stdlist

2
推荐指数
1
解决办法
508
查看次数

我如何声明和初始化这个 map&lt;pair&lt;int, int&gt;, bool&gt;?

当我尝试使用Key aspair<pair<int, int>, bool和Value as创建地图数据结构时int。

  • 在 xcode 上编译时,构建失败并出现链接器错误
  • 在 cpp.sh 或 Godbolt.org 等网站上编译时,它会抛出模板 args 错误

这是代码:

#include <iostream>
#include <vector>
#include <map>
#include <utility>
using namespace std;

typedef std::pair<int,int> pair;

struct comp
{
    template<typename T>
    bool operator()(const T &l, const T &r) const
    {
        if (l.first == r.first)
            return l.second > r.second;

        return l.first < r.first;
    }
};

int main()
{
    
    map<pair,bool,comp> mp = 
    {
        {std::make_pair<4,0>,true},
        {std::make_pair<4,1>,true}
    }; //Initializing

    mp.insert(make_pair(3,0),true); //Inserting

    return 0; 
} …
Run Code Online (Sandbox Code Playgroud)

c++ dictionary stl data-structures

0
推荐指数
1
解决办法
147
查看次数

标签 统计

c++ ×2

stl ×2

data-structures ×1

dictionary ×1

move ×1

rvalue ×1

stdlist ×1